package com.hjm.project.merchantInfo.merchantInfo.service.impl;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import com.google.common.collect.Maps;
import com.hjm.common.utils.bean.BeanUtils;
import com.hjm.project.formalPos.formalPos.domain.QcfFormalPosVo;
import com.hjm.project.merchantInfo.merRecord.domain.MerUpdateAreaRecord;
import com.hjm.project.merchantInfo.merchantInfo.util.UpdateMerUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


import com.alibaba.fastjson.JSON;
import com.hjm.common.exception.BusinessException;
import com.hjm.common.utils.*;
import com.hjm.common.utils.fastdfs.FastDFSClient;
import com.hjm.common.utils.request.AutoLoadData;
import com.hjm.common.utils.request.HttpClientUtil;
import com.hjm.common.utils.request.HttpClientUtils;
import com.hjm.common.utils.security.ShiroUtils;
import com.hjm.common.utils.yh.Utils;
import com.hjm.framework.aspectj.lang.annotation.DataSource;
import com.hjm.framework.aspectj.lang.enums.DataSourceType;
import com.hjm.framework.web.domain.AjaxResult;
import com.hjm.project.accounts.accounts.domain.Accounts;
import com.hjm.project.accounts.accounts.mapper.AccountsMapper;
import com.hjm.project.agentInfo.agentInfo.domain.AgentInfo;
import com.hjm.project.agentInfo.agentInfo.mapper.AgentInfoMapper;
import com.hjm.project.area.mapper.AreaMapper;
import com.hjm.project.clientImg.clientImg.domain.ClientImg;
import com.hjm.project.clientImg.clientImg.mapper.ClientImgMapper;
import com.hjm.project.formalPos.branchPos.domain.BranchPos;
import com.hjm.project.formalPos.branchPos.mapper.BranchPosMapper;
import com.hjm.project.formalPos.formalPos.domain.FormalPos;
import com.hjm.project.formalPos.formalPos.domain.FormalPosVo;
import com.hjm.project.formalPos.formalPos.mapper.FormalPosMapper;
import com.hjm.project.merchantInfo.merRecord.domain.MerRecord;
import com.hjm.project.merchantInfo.merRecord.mapper.MerRecordMapper;
import com.hjm.project.merchantInfo.merSyncRecord.domain.MerSyncRecord;
import com.hjm.project.merchantInfo.merSyncRecord.mapper.MerSyncRecordMapper;
import com.hjm.project.merchantInfo.merchantInfo.domain.*;
import com.hjm.project.merchantInfo.newMerRecord.domain.NewMerRecord;
import com.hjm.project.merchantInfo.newMerRecord.mapper.NewMerRecordMapper;
import com.hjm.project.merchantInfo.total.domain.MerchantTotal;
import com.hjm.project.merchantInfo.total.mapper.MerchantTotalMapper;
import com.hjm.project.terminal.library.domain.TerminalLibrary;
import com.hjm.project.terminal.library.mapper.TerminalLibraryMapper;
import com.yxhd.encrypt.EncryptUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.stereotype.Service;
import com.hjm.project.merchantInfo.merchantInfo.mapper.MerchantInfoMapper;
import com.hjm.project.merchantInfo.merchantInfo.service.IMerchantInfoService;
import com.hjm.common.utils.text.Convert;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;

import static com.hjm.common.utils.yh.QbMerUtil.toChar;

/**
 * 商户信息Service业务层处理
 *
 * @author LOVE
 * @date 2020-11-23
 */
@Service
public class MerchantInfoServiceImpl implements IMerchantInfoService {
    @Resource
    private MerchantInfoMapper merchantInfoMapper;
    @Resource
    private AreaMapper areaMapper;
    @Resource
    private AccountsMapper accountsMapper;
    @Resource
    private AgentInfoMapper agentInfoMapper;
    @Resource
    private FormalPosMapper formalPosMapper;
    @Resource
    private BranchPosMapper branchPosMapper;
    @Resource
    private MerRecordMapper merRecordMapper;
    @Resource
    private MerchantTotalMapper merchantTotalMapper;
    @Resource
    private TerminalLibraryMapper terminalLibraryMapper;
    @Resource
    private NewMerRecordMapper newMerRecordMapper;
    @Resource
    private ClientImgMapper clientImgMapper;
    @Resource
    private MerSyncRecordMapper merSyncRecordMapper;

    private DecimalFormat df = new DecimalFormat("####0.00");
    private DecimalFormat df3 = new DecimalFormat("####0.000");
    private String[] folderArray = {"upload", "upload1", "upload2", "upload3", "upload4", "upload5", "upload6", "upload7", "upload8", "upload10", "upload12", "upload13", "upload25"};

    /**
     * 查询商户信息
     *
     * @param merno 商户信息ID
     * @return 商户信息
     */
    @Override
    public MerchantInfo selectMerchantInfoById(String merno) {
        return merchantInfoMapper.selectMerchantInfoById(merno);
    }

    /**
     * 查询商户信息列表
     *
     * @param merchantInfo 商户信息
     * @return 商户信息
     */
    @Override
    public List<MerchantInfo> selectMerchantInfoList(MerchantInfo merchantInfo) {
        return merchantInfoMapper.selectMerchantInfoList(merchantInfo);
    }

    @Override
    public List<Map> selectMerchantInfoList1(MerchantInfo merchantInfo) {
        return merchantInfoMapper.selectMerchantInfoList1(merchantInfo);
    }

    @Override
    public int updateMerchantSync(String ldMerNo) {
        return merchantInfoMapper.updateMerchantSync(ldMerNo);
    }

    /**
     * 数据管理-商户查询
     *
     * @param merchantInfo 商户信息
     * @return 商户信息
     */
    @Override
    public List<MerchantInfo> selectDataMerInfoList(MerchantInfo merchantInfo) {
        return merchantInfoMapper.selectDataMerInfoList(merchantInfo);
    }

    /**
     * 新增商户信息
     *
     * @param merchantInfo 商户信息
     * @return 结果
     */
    @Override
    public int insertMerchantInfo(MerchantInfo merchantInfo) {
        return merchantInfoMapper.insertMerchantInfo(merchantInfo);
    }

    /**
     * 修改商户信息
     *
     * @param merchantInfo 商户信息
     * @return 结果
     */
    @Override
    public int updateMerchantInfo(MerchantInfo merchantInfo) {
        return merchantInfoMapper.updateMerchantInfo(merchantInfo);
    }

    /**
     * 删除商户信息对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteMerchantInfoByIds(String ids) {
        return merchantInfoMapper.deleteMerchantInfoByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除商户信息信息
     *
     * @param merno 商户信息ID
     * @return 结果
     */
    @Override
    public int deleteMerchantInfoById(String merno) {
        return merchantInfoMapper.deleteMerchantInfoById(merno);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult saveCancel(MerchantInfo merchantInfo) {
        try {
            MerchantInfo info = merchantInfoMapper.selectMerchantInfoById(merchantInfo.getMerno());
            String merStatus = String.valueOf(info.getMerStatus());
            if ("1".equals(merStatus)) {
                return AjaxResult.error("该商户已经注销不能注销");
            }
            merchantInfo.setMerStatus(1L);
            int result = merchantInfoMapper.updateMerchantInfo(merchantInfo);
            if (result > 0) {
                if (merchantInfo.getLdMerno() != null) {
                    Map data = new HashMap();
                    data.put("mchtNo", merchantInfo.getLdMerno());
                    data.put("applyCancelType", "1");
                    //注销上游
                    String send = HttpUtils.send(AutoLoadData.applyCancelStop, JSONObject.parseObject(data.toString()), "utf-8");
                }
                return AjaxResult.success();
            } else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateAddress(MerchantInfo merchantInfo, Map<String, String> params) throws Exception {
        //获取商户信息
        MerchantInfo mer = merchantInfoMapper.selectMerchantInfoById(merchantInfo.getMerno());
        if (mer.getMerTb() != null && mer.getMerTb() == 2){
            return AjaxResult.warn("不允许修改重庆商户注册地址");
        }
        if(!mer.getMerStatus().toString().equals("0")){
            return AjaxResult.warn("非正式商户，无法修改商户注册地址");
        }
        String province = params.get("province");
        String city = params.get("city");
        String area = params.get("area");
        if (StringUtils.isEmpty(province) || StringUtils.isEmpty(city) || StringUtils.isEmpty(area)) {
            return AjaxResult.error("省市区不能为空");
        }
        params.put("area_type", "3");
        params.put("qu", params.get("area"));
        String areaName = areaMapper.getAreaName(params);
        merchantInfo.setMerArea(areaName);
        merchantInfo.setMerCode(province + "," + city + "," + area);
        int result = merchantInfoMapper.updateMerchantInfo(merchantInfo);

        Accounts at = new Accounts();
        at.setSeqId(mer.getMerno());
        Accounts accounts = accountsMapper.selectAccounts(at);


        JSONObject request1 = new JSONObject();
        request1.put("settlTN", "0");
        request1.put("mchtNo", mer.getLdMerno());
        request1.put("settleAcctNm", mer.getLegalName());
        request1.put("settleAcctNo", EncryptUtils.getDecrypt(accounts.getScreenNum()));
        request1.put("settleIdentifyNo", EncryptUtils.getDecrypt(mer.getLegalCerno()));
        request1.put("settleBindTel", EncryptUtils.getDecrypt(mer.getLinkPhone()));
        String[] areas = merchantInfo.getMerCode().split(",");
        request1.put("addrProvince",areas[0]);
        request1.put("addrCity",areas[1]);
        request1.put("addrCounty",areas[2]);
        request1.put("addr",merchantInfo.getMerArea());

        Map<String, Object> requestMap = Maps.newHashMap();
        requestMap.put("mchtJson", JSONObject.toJSONString(request1));
        requestMap.put("brhJson", UpdateMerUtils.getPartnerJson());

        //发送请求
        System.out.println(requestMap);
        String getMerchant = "";
        //更改上游商户注册地址
        getMerchant = HttpClientUtil.doPost(AutoLoadData.sendLdMerSyncMes, requestMap);
        System.out.println("响应===============》" + getMerchant);
        if(!JSONObject.parseObject(getMerchant).get("status").toString().equals("0000")){
            return AjaxResult.error(JSONObject.parseObject(getMerchant).getString("msg"));
        }

        if (result > 0) {
            /**保存注册地址修改记录*/
            Map record = new HashMap();
            record.put("merno",mer.getMerno());
            record.put("merName",mer.getMerName());
            record.put("merType",mer.getMerType());
            record.put("merStatus",mer.getMerStatus());
            record.put("oldAddress",mer.getMerArea());
            record.put("oldDetailed",mer.getMerAddress());
            record.put("newAddress",merchantInfo.getMerArea());
            record.put("newDetailed",merchantInfo.getMerAddress());
            record.put("addMan",params.get("addMan"));
            merchantInfoMapper.insertEditAddressRecord(record);
            //拼接参数

            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateBank(Map<String, String> params) {
        Accounts accounts = new Accounts();
        accounts.setSeqId(params.get("merno"));
        accounts.setScreenName(params.get("screenName"));
        try {
            accounts.setScreenIdnum(EncryptUtils.getEncrypt(params.get("screenIdnum")));
            accounts.setResphone(EncryptUtils.getEncrypt(params.get("resphone")));
            accounts.setScreenNum(EncryptUtils.getEncrypt(params.get("screenNum")));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        accounts.setBankHeadname(params.get("headBank"));
        accounts.setBankName(params.get("branchBank"));
        accounts.setBankNum(params.get("subbranchId"));
        Map<String, Object> areaP = new HashMap();
        areaP.put("area_code", params.get("province"));
        areaP.put("area_type", "0");
        Map<String, Object> pMap = areaMapper.findQBAreaName(areaP);
        areaP.put("area_code", params.get("city"));
        areaP.put("area_type", "1");
        Map<String, Object> cMap = areaMapper.findQBAreaName(areaP);
        accounts.setAreaName(pMap.get("AREA_NAME") + "," + cMap.get("AREA_NAME"));
        accounts.setBankAddress(params.get("province") + "," + params.get("city"));
        accounts.setDaMarker(2);
        int result = accountsMapper.updateAccountsBySeqId(accounts);
        if (result > 0) {
            merchantInfoMapper.updateMerchantCardBag(params);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateSettle(MerchantInfo merchantInfo) {
        //调用钱宝修改接口
        Map<String, String> params = new HashMap<>();
        //结算类型
        params.put("settlTN", merchantInfo.getSettleCycle());
        //实时生效
        params.put("rateFlag", "1");
        //钱宝商户号
        params.put("mchtNo", merchantInfo.getLdMerno());
        params.put("originalMid", merchantInfo.getMerno());
        params.put("busType", "1");
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("merchantInfo", params);
        //TODO 修改商户结算类型(钱宝)
        JSONObject jsonObject = HttpClientUtils.sendHttpPostJson("http://127.0.0.1:8895/updateMerchant", JSONObject.toJSONString(requestMap));
        if (jsonObject == null || 200 != jsonObject.getInteger("responseCode")) {
            return AjaxResult.error("上游响应失败");
        }
        JSONObject responseVal = JSONObject.parseObject(jsonObject.getString("responseVal"));
        if ("A10".equals(responseVal.getString("code"))) {
            int result = merchantInfoMapper.updateMerchantInfo(merchantInfo);
            return AjaxResult.success();
        } else {
            return AjaxResult.error("上游失败");
        }

    }

    @Override
    public Map findMerchantInfoByMerNo(String merno) throws Exception {
        Map resultMap = merchantInfoMapper.findMerchatInfoByMerno(merno);
        resultMap.put("LINKE_PHONE_DES", resultMap.get("LINK_PHONE"));
        //解密字段
        decrypt(resultMap, "LEGAL_CERNO");
        decrypt(resultMap, "LINK_PHONE");
        decrypt(resultMap, "SCREEN_NUM");
        decrypt(resultMap, "SCREEN_IDNUM");
        decrypt(resultMap, "RESPHONE");
        return resultMap;
    }

    @Override
    public List<MerchantInfo> findMerchantInfoByMerNo(MerchantInfo merchantInfo) throws Exception {
        return merchantInfoMapper.selectMerchantInfoList(merchantInfo);
    }

    private void decrypt(Map resultMap, String key) throws Exception {
        if (resultMap.containsKey(key) && !Utils.isEmpty(String.valueOf(resultMap.get(key)))) {
            if (String.valueOf(resultMap.get(key)).indexOf("*") == -1) {
                if ("LINK_PHONE".equals(key)) {
                    if (resultMap.get(key) != null && resultMap.get(key).toString().length() > 11) {
                        resultMap.put(key, EncryptUtils.getDecrypt(String.valueOf(resultMap.get(key))));
                    }
                } else {
                    resultMap.put(key, EncryptUtils.getDecrypt(String.valueOf(resultMap.get(key))));
                }
            }
        }
    }

    @Override
    public List<Map<String, Object>> getMerchantRate(String merno) {
        return merchantInfoMapper.findMerchantRateByMerno(merno);
    }


    @Override
    public MerchantShow getMerchantInfoShow(String merno) {
        return merchantInfoMapper.findMerchantInfoShowByMerno(merno);
    }


    /**
     * @Param [merNo 要迁移的商户编号, agentNum 要迁移的代理商编号]
     * @Return int
     */
    @Transactional
    @Override
    public AjaxResult merMigrateUpdate(String merNo, String agentNum) {
        try {
            LogUtils.logInfo("开始迁移商户:" + merNo + "----" + "代理商编号:" + agentNum);
            //获取商户信息
            MerchantInfo merchantInfo = merchantInfoMapper.selectMerchantInfoById(merNo);
            //原服务商编号
            String thisAgentNum = merchantInfo.getAgentNo();
            //原代理编号和要迁移代理不可相同
            if (agentNum.equals(thisAgentNum)) {
                LogUtils.logInfo("已经所属目标服务商,不可重复迁移");
                return AjaxResult.error("已经所属目标服务商,不可重复迁移");

            }
            //要迁移的服务商信息
            AgentInfo agentInfo = agentInfoMapper.selectAgentInfoById(thisAgentNum);
            if (agentInfo == null) {
                LogUtils.logInfo("服务商不存在");
                return AjaxResult.error("服务商不存在");
            }
            // 0 正常代理
            if (!"0".equals(agentInfo.getAgentStatus())) {
                LogUtils.logInfo("服务商状态非正常,请先确认服务商状态");
                return AjaxResult.error("服务商状态非正常代理,请先确认服务商状态");
            }
            //修改迁移信息
            MerchantInfo mer = new MerchantInfo();
            mer.setIsMigrate(1);
            mer.setOriginalAgentNum(thisAgentNum);
            mer.setAgentNo(agentNum);
            mer.setMigrateDate(DateUtils.getTime());
            mer.setMerno(merNo);
            LogUtils.logInfo("迁移参数：" + JSON.toJSONString(mer));
            int i = merchantInfoMapper.updateMerchantInfo(mer);
            if (i > 0) {
                //迁移branch_pos 和 formal_pos
                Map<String, Object> formalPos = merchantInfoMapper.getFormalPosByMerno(merNo);
                if (ObjectUtils.allNotNull(formalPos)) {
                    Map<String, Object> request = new HashMap<>();
                    request.put("posno", formalPos.get("POSNO"));
                    request.put("agentNum", agentNum);
                    i = merchantInfoMapper.updateBranchPos(request);
                    if (i > 0) {
                        i = merchantInfoMapper.updateFormalPos(request);
                    }
                }
            }
            if (i <= 0) {
                LogUtils.logInfo("迁移失败:修改结果[ " + i + " ]");
                return AjaxResult.error("迁移失败");
            }

            //商户迁移记录
            MerRecord merRecord = new MerRecord();
            merRecord.setMerNo(merNo);
            merRecord.setAgentNum(thisAgentNum);
            merRecord.setNewAgentNum(agentNum);
            merRecord.setNote("商户迁移");
            merRecord.setCreateDate(DateUtils.getDateTime());
            merRecord.setType("2");
            merRecord.setOperation(ShiroUtils.getSysUser().getObjNo());
            merRecordMapper.insertMerRecord(merRecord);

         /*   //目标代理商
            valiIsCkMer(agentNum);
            //当前代理商
            valiIsCkMer(thisAgentNum);*/

        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.logInfo("迁移异常" + e);
            return AjaxResult.error("迁移异常");
        }
        LogUtils.logInfo("迁移成功" + merNo + "----" + "代理商编号:" + agentNum);
        return AjaxResult.success("迁移成功");

    }

    /**
     * 验证当前代理商是佛展业端管理商户
     *
     * @param agentNum
     * @Param [agentNum]
     * @Return int
     */
    @Override
    public void valiIsCkMer(String agentNum) {
        Integer isExistence = 2;
        //获取代理信息
        AgentInfo agentInfo = agentInfoMapper.selectAgentInfoById(agentNum);

        //获取代理的终端,只有一个终端才可以是展业端管理商户
        BranchPos bp = new BranchPos();
        bp.setAgentNum(Long.parseLong(agentNum));
        List<BranchPos> branchPos = branchPosMapper.selectBranchPosList(bp);

        //展业端管理下的商户只有一个 并且 商户法人和代理法人是一致的 并且代理只有一台机器
        //查看当前代理下的商户是否只有一个
        MerchantInfo mer = new MerchantInfo();
        mer.setAgentNo(agentNum);
        List<MerchantInfo> merchantInfos = merchantInfoMapper.selectDataMerInfoList(mer);
        //代理下有一个商户 并且 有一个终端
        if (CollectionUtils.isNotEmpty(merchantInfos) && merchantInfos.size() == 1 &&
                CollectionUtils.isNotEmpty(branchPos) && branchPos.size() == 1) {
            //当满足基本条件后 查看是否是同一个人
            if (agentInfo.getCommissary().equals(merchantInfos.get(0).getLegalName()) &&
                    agentInfo.getShowIdentitynum().equals(merchantInfos.get(0).getShowLegalcerno())) {
                isExistence = 1;
            } else {
                isExistence = 2;
            }
        } else {
            isExistence = 2;
        }

        //更新代理商标识
        AgentInfo updateAgent = new AgentInfo();
        updateAgent.setAgentNum(agentNum);
        updateAgent.setIsExistence(isExistence);
        agentInfoMapper.updateAgentInfo(updateAgent);
        //更新终端标识，如果是展业端管理商户那么终端底薪计划所属类型为上级
        //底薪计划所属代理商编号 为上级
        if (isExistence == 1 && agentInfo.getBelongAgent() != Long.parseLong("100000000")) {
            BranchPos bpUpdate = new BranchPos();
            bpUpdate.setBelongToAgentNum(agentInfo.getBelongAgent().intValue());
            bpUpdate.setBelongToType(2);
            bpUpdate.setMachineNum(branchPos.get(0).getMachineNum());
            branchPosMapper.updatePos(bpUpdate);
        }

    }

    /**
     * 商户换机
     *
     * @param param Map
     * @return int
     * @throws Exception e
     */
    @Override
    @Transactional
    public int merReplacePos(Map<String, String> param) throws Exception {
        try {
            //原终端SN
            String posNo = param.get("posNo");
            //新的终端SN
            String newPosNo = param.get("newPosNo");
            MerchantInfo mi = new MerchantInfo();
            mi.setMerno(String.valueOf(param.get("merNo")));
            //获取商户的信息
            MerchantInfo merchantInfo = merchantInfoMapper.selectMerchantInfoById(mi.getMerno());
            //查看新的终端是否是当前商户代理的机器
            BranchPos isBp = new BranchPos();
            isBp.setMachineNum(newPosNo);
            List<BranchPos> bpInfo = branchPosMapper.selectBranchPosList(isBp);
            if (CollectionUtils.isEmpty(bpInfo)) {
                throw new BusinessException("新终端不存在,请确认SN编号");
            }
            //新终端信息
            BranchPos newBp = bpInfo.get(0);
            //新终端是否是当前商户的代理
            if (!merchantInfo.getAgentNo().equals(newBp.getAgentNum().toString())) {
                throw new BusinessException("当前终端非商户所属代理所持有");
            }
            //绑定状态和激活状态 其中一个为1说明已使用过不可换机
            if (newBp.getIsbound().intValue() == 1 || newBp.getActivate().intValue() == 1) {
                throw new BusinessException("当前终端已使用,请重新选择");
            }

            Map<String, Object> requestMap = new HashMap<>();
            LogUtils.logInfo("开始进行商户解绑:" + posNo);
            //上送钱宝，终端解绑
            requestMap.put("termId", merchantInfo.getBankterno());
            requestMap.put("sn", posNo);
            String s1 = JSONObject.toJSONString(requestMap);
            //TODO 商户管理-所有商户-钱宝终端解绑
            JSONObject jsonObject = HttpClientUtils.sendHttpPostJson(AutoLoadData.unbingPosUrl, s1);
            LogUtils.logInfo("商户解绑返回结果:" + param.get("newPosNo"));
            if (jsonObject == null) {
                LogUtils.logInfo("商户解绑接口返回为 NULL");
                throw new BusinessException("商户解绑接口返回为 NULL");
            }
            String responseCode = jsonObject.getString("responseCode");
            Map<String, String> jsonMap = JSONObject.parseObject(jsonObject.getString("responseVal"), Map.class);
            String unBindMessage = jsonMap.get("message");
            if (!"200".equals(responseCode)) {
                LogUtils.logInfo("商户解绑响应码非200" + responseCode);
                throw new BusinessException("商户解绑响应码非200:" + responseCode);
            }
            if (!"A10".equals(jsonMap.get("code"))) {
                LogUtils.logInfo("商户解绑失败" + unBindMessage);
                throw new BusinessException("商户解绑失败:" + unBindMessage);
            }
            /***************************绑定终端********************************/
            LogUtils.logInfo("开始进行商户绑定:" + param.get("newPosNo"));
            //上送钱宝，绑定终端
            requestMap.put("sn", newPosNo);
            requestMap.put("termId", merchantInfo.getBankterno());
            //TODO 商户管理-所有商户-钱宝终端绑定
            String result = HttpUtilClient.doPostJson(AutoLoadData.bingPosUrl, null, requestMap);
            LogUtils.logInfo("商户绑定返回结果:" + result);
            if (StringUtils.isEmpty(result)) {
                LogUtils.logInfo("绑定终端接口返回为NULL");
                throw new BusinessException("接口返回为NULL");
            }
            JSONObject jsonObjectBind = JSONObject.parseObject(result);
            if ("A10".equals(jsonObjectBind.get("code"))) {
                //获取原终端SN的虚拟POS编号
                BranchPos original = new BranchPos();
                original.setMachineNum(posNo);
                BranchPos branchPos1 = branchPosMapper.selectBranchPosList(original).get(0);
                //更新代理分配pos表中的信息 新旧终端互换SN（只替换SN编号）
                BranchPos branchPos = new BranchPos();
                branchPos.setMachineNum(newPosNo);
                branchPos.setId(branchPos1.getId());
                int i = branchPosMapper.updatePosInfo(branchPos);
                //把根据新终端的虚拟终端编号 更新SN编号为老终端的SN
                branchPos.setMachineNum(posNo);
                branchPos.setId(newBp.getId());
                int i2 = branchPosMapper.updatePosInfo(branchPos);
                if (i2 <= 0 || i <= 0) {
                    throw new BusinessException("更换终端信息失败");
                }
                //更上商户的真实终端信息（只替换SN编号）
                FormalPos fl = new FormalPos();
                fl.setId(Long.parseLong(param.get("id")));
                fl.setMachineNum(newPosNo);
                fl.setNote("原终端SN:" + posNo + "更换为:" + newPosNo);
                int i1 = formalPosMapper.updateFormalPos(fl);
                if (i1 <= 0 || i <= 0) {
                    LogUtils.logInfo("商户换机处理完成");
                    throw new BusinessException("换机失败,请重试");
                }
                //旧终端
                TerminalLibrary oldtl = terminalLibraryMapper.selectTerminalLibraryBySn(posNo);
                //新终端
                TerminalLibrary newtl = terminalLibraryMapper.selectTerminalLibraryBySn(newPosNo);
                TerminalLibrary terminalLibrary = new TerminalLibrary();
                //修改旧终端sn为新sn
                terminalLibrary.setId(oldtl.getId());
                terminalLibrary.setMachineNum(newPosNo);
                int t1 = terminalLibraryMapper.updateTerminalLibrary(terminalLibrary);
                //修改新终端sn为旧sn
                terminalLibrary.setId(newtl.getId());
                terminalLibrary.setMachineNum(posNo);
                int t2 = terminalLibraryMapper.updateTerminalLibrary(terminalLibrary);
                if (t1 <= 0 || t2 <= 0) {
                    throw new BusinessException("更换终端信息失败");
                }
                //商户换机记录
                MerRecord merRecord = new MerRecord();
                merRecord.setMerNo(param.get("merNo"));
                merRecord.setSn(posNo);
                merRecord.setNewSn(newPosNo);
                merRecord.setNote("商户换机");
                merRecord.setCreateDate(DateUtils.getDateTime());
                merRecord.setType("1");
                merRecord.setOperation(ShiroUtils.getSysUser().getObjNo());
                merRecordMapper.insertMerRecord(merRecord);
            } else {
                throw new BusinessException(jsonObjectBind.get("message").toString());
            }
            LogUtils.logInfo("商户换机处理完成");
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return 1;
    }

    /**
     * 商户换机GB
     *
     * @param param Map
     * @return int
     * @throws Exception e
     */
    @Override
    @Transactional
    public int merReplacePosGB(Map<String, String> param) throws Exception {
        try {
            //原终端SN
            String posNo = param.get("posNo");
            //新的终端SN
            String newPosNo = param.get("newPosNo");
            MerchantInfo mi = new MerchantInfo();
            mi.setMerno(String.valueOf(param.get("merNo")));
            //获取商户的信息
            MerchantInfo merchantInfo = merchantInfoMapper.selectMerchantInfoById(mi.getMerno());
            //查看新的终端是否是当前商户代理的机器
            BranchPos isBp = new BranchPos();
            isBp.setMachineNum(newPosNo);
            List<BranchPos> bpInfo = branchPosMapper.selectBranchPosList(isBp);
            if (CollectionUtils.isEmpty(bpInfo)) {
                throw new BusinessException("新终端不存在,请确认SN编号");
            }
            //新终端信息
            BranchPos newBp = bpInfo.get(0);
            //新终端是否是当前商户的代理
            if (!merchantInfo.getAgentNo().equals(newBp.getAgentNum().toString())) {
                throw new BusinessException("当前GB终端非商户所属代理所持有");
            }
            //绑定状态和激活状态 其中一个为1说明已使用过不可换机
            if (newBp.getIsbound().intValue() == 1 || newBp.getActivate().intValue() == 1) {
                throw new BusinessException("当前GB终端已使用,请重新选择");
            }

            LogUtils.logInfo("开始进行商户GB换机:" + posNo);

            /***************************绑定终端********************************/
            //获取原终端SN的虚拟POS编号
            BranchPos original = new BranchPos();
            original.setMachineNum(posNo);
            BranchPos branchPos1 = branchPosMapper.selectBranchPosList(original).get(0);
            //更新代理分配pos表中的信息 新旧终端互换SN（只替换SN编号）
            BranchPos branchPos = new BranchPos();
            branchPos.setMachineNum(newPosNo);
            branchPos.setId(branchPos1.getId());
            int i = branchPosMapper.updatePosInfo(branchPos);
            //把根据新终端的虚拟终端编号 更新SN编号为老终端的SN
            branchPos.setMachineNum(posNo);
            branchPos.setId(newBp.getId());
            int i2 = branchPosMapper.updatePosInfo(branchPos);
            if (i2 <= 0 || i <= 0) {
                throw new BusinessException("GB更换终端信息失败");
            }
            //更上商户的真实终端信息（只替换SN编号）
            FormalPos fl = new FormalPos();
            fl.setId(Long.parseLong(param.get("id")));
            fl.setMachineNum(newPosNo);
            fl.setNote("GB原终端SN:" + posNo + "更换为:" + newPosNo);
            int i1 = formalPosMapper.updateFormalPos(fl);
            if (i1 <= 0 || i <= 0) {
                LogUtils.logInfo("商户换机GB处理完成");
                throw new BusinessException("GB换机失败,请重试");
            }
            //旧终端
            TerminalLibrary oldtl = terminalLibraryMapper.selectTerminalLibraryBySn(posNo);
            //新终端
            TerminalLibrary newtl = terminalLibraryMapper.selectTerminalLibraryBySn(newPosNo);
            TerminalLibrary terminalLibrary = new TerminalLibrary();
            //修改旧终端sn为新sn
            terminalLibrary.setId(oldtl.getId());
            terminalLibrary.setMachineNum(newPosNo);
            int t1 = terminalLibraryMapper.updateTerminalLibrary(terminalLibrary);
            //修改新终端sn为旧sn
            terminalLibrary.setId(newtl.getId());
            terminalLibrary.setMachineNum(posNo);
            int t2 = terminalLibraryMapper.updateTerminalLibrary(terminalLibrary);
            if (t1 <= 0 || t2 <= 0) {
                throw new BusinessException("更换终端信息失败");
            }
            //商户换机记录
            MerRecord merRecord = new MerRecord();
            merRecord.setMerNo(param.get("merNo"));
            merRecord.setSn(posNo);
            merRecord.setNewSn(newPosNo);
            merRecord.setNote("商户换机");
            merRecord.setCreateDate(DateUtils.getDateTime());
            merRecord.setType("1");
            merRecord.setOperation(ShiroUtils.getSysUser().getObjNo());
            merRecordMapper.insertMerRecord(merRecord);

            LogUtils.logInfo("商户换机GB处理完成");
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return 1;
    }

    /**
     * 处理接口库的换机操作
     *
     * @Param [param]
     * @Return int
     */
    @Override
    @DataSource(value = DataSourceType.SLAVE)
    public void manageJkPosKeyInfo(Map<String, String> param) throws Exception {
        try {
            //获取老终端信息
            HashMap old = new HashMap();
            old.put("sn", param.get("oldSn"));
            Map oldSnInfo = merchantInfoMapper.selectJkPosKeyInfo(old);
            if (MapUtils.isEmpty(oldSnInfo)) {
                throw new BusinessException("接口库获取不到旧终端信息");
            }
            //获取新终端信息
            old.put("sn", param.get("newSn"));
            Map newSnInfo = merchantInfoMapper.selectJkPosKeyInfo(old);
            if (MapUtils.isEmpty(newSnInfo)) {
                throw new BusinessException("接口库获取不到新终端信息");
            }
            //由于 SN 和 posno 唯一约束要修改一个替换值进行互换SN
            //根据虚拟终端号修改SN
            HashMap oldUpdate = new HashMap();
            oldUpdate.put("sn", "0");
            oldUpdate.put("terno", oldSnInfo.get("TERNO"));
            int i = merchantInfoMapper.updateJkPosKeyInfo(oldUpdate);
            if (i <= 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new BusinessException("商户换机接口库第一步修改失败");
            }
            //修改新终端的SN为老终端
            HashMap newSNUpdate = new HashMap();
            newSNUpdate.put("sn", oldSnInfo.get("SN"));
            newSNUpdate.put("terno", newSnInfo.get("TERNO"));
            int j = merchantInfoMapper.updateJkPosKeyInfo(newSNUpdate);
            if (j <= 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new BusinessException("商户换机接口库第二步修改失败");
            }
            //再修改老终端的状态为新终端
            HashMap newInfo = new HashMap();
            newInfo.put("sn", newSnInfo.get("SN"));
            newInfo.put("terno", oldSnInfo.get("TERNO"));
            int k = merchantInfoMapper.updateJkPosKeyInfo(newInfo);
            if (k <= 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new BusinessException("商户换机接口库第三步修改失败");
            }
            //更新tpos表信息
            HashMap tposParams = new HashMap();
            tposParams.put("merno", param.get("merno"));
            int p = merchantInfoMapper.updateJkTpos(tposParams);
            if (p <= 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new BusinessException("商户换机接口库重新加载商户信息失败");
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            LogUtils.logInfo("接口库换机异常:" + e);
            throw e;
        }
    }

    /**
     * 处理接口库的GB换机操作
     *
     * @Param [param]
     * @Return int
     */
    @Override
    @DataSource(value = DataSourceType.SLAVE)
    public void manageJkPosKeyInfoGB(Map<String, String> param) throws Exception {
        try {
            //获取老终端信息
            HashMap old = new HashMap();
            old.put("sn", param.get("oldSn"));
            Map oldSnInfo = merchantInfoMapper.selectJkPosKeyInfo(old);
            if (MapUtils.isEmpty(oldSnInfo)) {
                throw new BusinessException("接口库获取不到旧终端信息");
            }
            //获取新终端信息
            old.put("sn", param.get("newSn"));
            Map newSnInfo = merchantInfoMapper.selectJkPosKeyInfo(old);
            if (MapUtils.isEmpty(newSnInfo)) {
                throw new BusinessException("接口库获取不到新终端信息");
            }
            //由于 SN 和 posno 唯一约束要修改一个替换值进行互换SN
            //根据虚拟终端号修改SN
            HashMap oldUpdate = new HashMap();
            oldUpdate.put("sn", "0");
            oldUpdate.put("terno", oldSnInfo.get("TERNO"));
            int i = merchantInfoMapper.updateJkPosKeyInfo(oldUpdate);
            if (i <= 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new BusinessException("商户换机接口库第一步修改失败");
            }
            //修改新终端的SN为老终端
            HashMap newSNUpdate = new HashMap();
            newSNUpdate.put("sn", oldSnInfo.get("SN"));
            newSNUpdate.put("terno", newSnInfo.get("TERNO"));
            int j = merchantInfoMapper.updateJkPosKeyInfo(newSNUpdate);
            if (j <= 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new BusinessException("商户换机接口库第二步修改失败");
            }
            //再修改老终端的状态为新终端
            HashMap newInfo = new HashMap();
            newInfo.put("sn", newSnInfo.get("SN"));
            newInfo.put("terno", oldSnInfo.get("TERNO"));
            int k = merchantInfoMapper.updateJkPosKeyInfo(newInfo);
            if (k <= 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new BusinessException("商户换机接口库第三步修改失败");
            }
            //更新tpos表信息
            HashMap tposParams = new HashMap();
            tposParams.put("merno", param.get("merno"));
            int p = merchantInfoMapper.updateJkTpos(tposParams);
            if (p <= 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new BusinessException("商户换机接口库重新加载商户信息失败");
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            LogUtils.logInfo("接口库换机异常:" + e);
            throw e;
        }
    }

    //根据商户编号查询商户信息
    @Override
    public MerchantShow getMerchantInfo(String merno) throws Exception {
        MerchantShow info = merchantInfoMapper.findMerchantInfoShowByMerno(merno);
        if (!Utils.IsNull(info.getScreen_num())) {
            info.setScreen_num(EncryptUtils.getDecrypt(info.getScreen_num()));
        }
        if (!Utils.IsNull(info.getScreen_idnum())) {
            info.setScreen_idnum(EncryptUtils.getDecrypt(info.getScreen_idnum()));
        }
        if (!Utils.IsNull(info.getResphone())) {
            info.setResphone(EncryptUtils.getDecrypt(info.getResphone()));
        }
        if (!Utils.IsNull(info.getLink_phone())) {
            info.setLink_phone(EncryptUtils.getDecrypt(info.getLink_phone()));
        }
        return info;
    }

    @Override
    public List<MerchantRateShow> getMerchantRateShow(String merno) {
        return merchantInfoMapper.findMerchantRateShowByMerno(merno);
    }

    /**
     * 获取商户最新的费率信息
     *
     * @Param [params]
     * @Return int
     */
    @Override
    public AjaxResult getMerNewchantRate(String merNo, String apply_id) throws Exception {
        JSONObject merchantJson = UpstreamMerInfo.getMerchant(merNo, apply_id, AutoLoadData.qbGetmerInfo);
        // JSONObject merchantJson = JSONObject.parseObject(UpstreamMerInfo.RESULT);
        if (merchantJson == null) {
            return AjaxResult.error("上游接口返回为空");
        }
        //接口的请求状态
        if (!"200".equals(merchantJson.getString("responseCode"))) {
            return AjaxResult.error("接口请求失败:" + merchantJson.getString("responseCode"));
        }
        //json内层数据(上游封装结果)
        Map<String, String> map = JSONObject.parseObject(merchantJson.getString("responseVal"), Map.class);
        if (org.apache.commons.collections4.MapUtils.isEmpty(map)) {
            return AjaxResult.error("接口返回数据为空");
        }
        //上游处理结果
        if (!"A10".equals(map.get("code"))) {
            return AjaxResult.error("上游处理数据失败,错误编号:" + map.get("code"));
        }
        //内层
        //{"responseCode":200,"responseVal":"{"code":"A10","message":"{"msg":"OK","termList":
        Map<String, Object> data = JSONObject.parseObject(map.get("message"), Map.class);
        if (!"OK".equals(data.get("msg"))) {
            return AjaxResult.error("数据错误:" + data.get("msg"));
        }
        String merchantInfo = JSONObject.toJSONString(data.get("merchantInfo"));
        MerchantDto merchantDto = JSONObject.parseObject(merchantInfo, MerchantDto.class);
        merchantDto.setSettleAcctNo(Utils.hiddenCard(merchantDto.getSettleAcctNo()));
        merchantDto.setSettleBindTel(Utils.phone(merchantDto.getSettleBindTel()));
        merchantDto.setCommTel(Utils.phone(merchantDto.getCommTel()));
        MerchantDto result = new BeanClassUtils<MerchantDto>().setDefaultValue(merchantDto);
        return new AjaxResult(AjaxResult.Type.SUCCESS, "", result);
    }

    /**
     * 同步重庆商户信息
     *
     * @param data
     * @Param [body]
     * @Return com.hjm.framework.web.domain.AjaxResult
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult syncMerInfo(JSONObject data) {
        MerchantInfoVo merchantInfoVo = null;
        FormalPosVo formalPosVo = null;
        JSONObject reqBody = data.getJSONObject("data");
        JSONObject merchant = reqBody.getJSONObject("merchant");
        JSONObject formalPos = merchant.getJSONObject("formalPos");
        try {
            //转换商户基本信息
            merchantInfoVo = new DataConvertor<MerchantInfoVo>() {
            }.format(merchant);
            merchantInfoVo.setMerTb(2);
            merchantInfoVo.setMerNature(merchantInfoVo.getMerNature() == 0 ? 0 : 1);
            //转换商户终端信息
            formalPosVo = new DataConvertor<FormalPosVo>() {
            }.format(formalPos);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }

        LogUtils.logInfo("开始进行同步数据");
        LogUtils.logInfo("请求数据:" + data.toJSONString());


        String posno = "";
        //查看当前终端是否入库
        TerminalLibrary ti = new TerminalLibrary();
        ti.setMachineNum(formalPosVo.getMachineNum());
        String posType = "-1";
        List<TerminalLibrary> terminalLibraries = terminalLibraryMapper.selectTerminalLibraryList(ti);
        if (CollectionUtils.isNotEmpty(terminalLibraries)) {
            posno = terminalLibraries.get(0).getPosno();
            posType = terminalLibraries.get(0).getType().toString();
        } else {
            //生成一个posno编号
            posno = terminalLibraryMapper.getPosNo().toString();
        }
        formalPosVo.setPosno(posno);
        formalPosVo.setStatus(0);

        //查看终端是否分配
        BranchPos querSn = new BranchPos();
        querSn.setMachineNum(formalPosVo.getMachineNum());
        List<BranchPos> branchPosList = branchPosMapper.selectBranchPosList(querSn);
        if (CollectionUtils.isNotEmpty(branchPosList)) {
            formalPosVo.setAgentNum(Integer.parseInt(branchPosList.get(0).getAgentNum().toString()));
            merchantInfoVo.setAgentNo(branchPosList.get(0).getAgentNum().toString());
        }
        try {
            //查看是否同步
            MerchantInfo mi = new MerchantInfo();
            mi.setLdMerno(merchantInfoVo.getLdMerno());
            List<MerchantInfo> merList = merchantInfoMapper.selectMerchantInfoList(mi);
            //查看终端是否存在
            FormalPos fpResult = formalPosMapper.selectFormalPosBySn(formalPosVo.getMachineNum());
            String merNo = "";
            int row = -1;
            if (CollectionUtils.isEmpty(merList)) {
                LogUtils.logInfo("新增同步:" + merchantInfoVo.getLdMerno());
                merNo = merchantInfoMapper.getMerNo();
                //设置商户编号
                merchantInfoVo.setMerno(merNo);
                //设置终端绑定商户编号
                formalPosVo.setMerno(merNo);
                row = merchantInfoMapper.insertMerchantInfoVo(merchantInfoVo);
                //商户附加表
                MerchantTotal mt = new MerchantTotal();
                mt.setMerno(merNo);
                mt.setAgentNum(merchantInfoVo.getAgentNo());
                merchantTotalMapper.insertMerchantTotal(mt);
            } else {
                formalPosVo.setMerno(merList.get(0).getMerno());
                LogUtils.logInfo("更新同步:" + merchantInfoVo.getLdMerno());
                row = merchantInfoMapper.updateMerchantInfoVo(merchantInfoVo);
            }

            if (row < 1) {
                LogUtils.logInfo("商户同步失败:" + merchantInfoVo.getLdMerno());
                return AjaxResult.success("商户同步失败");
            }


            formalPosVo.setPosType(Integer.parseInt(posType));
            //绑定终端信息
            if (fpResult == null) {
                row = formalPosMapper.insertFormalPosVo(formalPosVo);
            } else {
                row = formalPosMapper.updateFormalPosVo(formalPosVo);
            }
            if (row < 1) {
                LogUtils.logInfo("商户同步失败:" + merchantInfoVo.getLdMerno());
                return AjaxResult.success("商户终端同步失败");
            }

            //更新终端状态
            BranchPos bp = new BranchPos();
            bp.setMachineNum(formalPosVo.getMachineNum());
            bp.setIsbound(Long.parseLong("1"));
            branchPosMapper.updatePos(bp);


            LogUtils.logInfo("同步成功:" + merchantInfoVo.getLdMerno());
            return AjaxResult.success("同步成功");
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("同步失败,请重试-" + merchantInfoVo.getLdMerno());
        }
    }

    /**
     * 同步重庆商户信息
     *
     * @param data
     * @Param [body]
     * @Return com.hjm.framework.web.domain.AjaxResult
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String,String> syncMerInfoJob(JSONObject data) {
        Map<String,String> result = new HashMap<>();
        result.put("code","200");
        result.put("msg","处理成功");

        MerchantInfoVo merchantInfoVo = null;
        FormalPosVo formalPosVo = null;
        JSONObject reqBody = data.getJSONObject("data");
        JSONObject merchant = reqBody.getJSONObject("merchant");
        JSONObject formalPos = merchant.getJSONObject("formalPos");
        if (StringUtils.isBlank(formalPos.getString("MACHINE_NUM"))){
            String formalPosList = merchant.getString("formalPosList");
            if (StringUtils.isNotBlank(formalPosList)) {
                JSONArray objects = JSONObject.parseArray(formalPosList);
                for (Object object : objects) {
                    JSONObject jsonObject = JSONObject.parseObject(object.toString());
                    if (jsonObject.getInteger("STATUS") == 0) {
                        formalPos = jsonObject;
                        break;
                    }
                }
            }


        }
        try {
            //转换商户基本信息
            merchantInfoVo = new DataConvertor<MerchantInfoVo>() {
            }.format(merchant);
            merchantInfoVo.setMerTb(2);
            merchantInfoVo.setMerNature(merchantInfoVo.getMerNature() == 0 ? 0 : 1);
            //转换商户终端信息
            formalPosVo = new DataConvertor<FormalPosVo>() {
            }.format(formalPos);
        } catch (Exception e) {
            result.put("code","300");
            result.put("msg",e.getMessage());
            return result;
        }

        LogUtils.logInfo("开始进行同步数据");
        LogUtils.logInfo("请求数据:" + data.toJSONString());

        if (StringUtils.isBlank(formalPosVo.getMachineNum())) {
            result.put("code","300");
            result.put("msg","未取到终端信息,不可同步");
            return result;
        }


        String posno = "";
        String posType = "-1";
        //查看当前终端是否入库
        TerminalLibrary ti = new TerminalLibrary();
        ti.setMachineNum(formalPosVo.getMachineNum());
        List<TerminalLibrary> terminalLibraries = terminalLibraryMapper.selectTerminalLibraryList(ti);
        if (CollectionUtils.isNotEmpty(terminalLibraries)) {
            posno = terminalLibraries.get(0).getPosno();
            posType = terminalLibraries.get(0).getType().toString();
        } else {
            //生成一个posno编号
            posno = terminalLibraryMapper.getPosNo().toString();
        }



        formalPosVo.setPosno(posno);
        formalPosVo.setStatus(0);

        //查看终端是否分配
        BranchPos querSn = new BranchPos();
        querSn.setMachineNum(formalPosVo.getMachineNum());
        List<BranchPos> branchPosList = branchPosMapper.selectBranchPosList(querSn);
        if (CollectionUtils.isNotEmpty(branchPosList)) {
            formalPosVo.setAgentNum(Integer.parseInt(branchPosList.get(0).getAgentNum().toString()));
            merchantInfoVo.setAgentNo(branchPosList.get(0).getAgentNum().toString());
        }
        try {
            //查看是否同步
            MerchantInfo mi = new MerchantInfo();
            mi.setLdMerno(merchantInfoVo.getLdMerno());
            List<MerchantInfo> merList = merchantInfoMapper.selectMerchantInfoList(mi);
            //查看终端是否存在
            FormalPos fpResult = formalPosMapper.selectFormalPosBySn(formalPosVo.getMachineNum());
            String merNo = "";
            int row = -1;
            if (CollectionUtils.isEmpty(merList)) {
                LogUtils.logInfo("新增同步:" + merchantInfoVo.getLdMerno());
                merNo = merchantInfoMapper.getMerNo();
                //设置商户编号
                merchantInfoVo.setMerno(merNo);
                //设置终端绑定商户编号
                formalPosVo.setMerno(merNo);
                row = merchantInfoMapper.insertMerchantInfoVo(merchantInfoVo);
                //商户附加表
                MerchantTotal mt = new MerchantTotal();
                mt.setMerno(merNo);
                mt.setAgentNum(merchantInfoVo.getAgentNo());
                merchantTotalMapper.insertMerchantTotal(mt);
            } else {
                formalPosVo.setMerno(merList.get(0).getMerno());
                LogUtils.logInfo("更新同步:" + merchantInfoVo.getLdMerno());
                row = merchantInfoMapper.updateMerchantInfoVo(merchantInfoVo);
            }

            if (row < 1) {
                LogUtils.logInfo("商户同步失败:" + merchantInfoVo.getLdMerno());
                result.put("code","300");
                result.put("msg","商户同步失败");
                return result;

            }


            formalPosVo.setPosType(Integer.parseInt(posType));

            //绑定终端信息
            if (fpResult == null) {
                row = formalPosMapper.insertFormalPosVo(formalPosVo);
            } else {
                row = formalPosMapper.updateFormalPosVo(formalPosVo);
            }
            if (row < 1) {
                LogUtils.logInfo("商户同步失败:" + merchantInfoVo.getLdMerno());
                result.put("code","300");
                result.put("msg","商户终端同步失败");
                return result;


            }

            //更新终端状态
            BranchPos bp = new BranchPos();
            bp.setMachineNum(formalPosVo.getMachineNum());
            bp.setIsbound(Long.parseLong("1"));
            branchPosMapper.updatePos(bp);


            LogUtils.logInfo("同步成功:" + merchantInfoVo.getLdMerno());
            result.put("code","200");
            result.put("msg","成功");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.put("code","300");
            result.put("msg","同步失败,请重试-" + merchantInfoVo.getLdMerno());
            return result;
        }
    }


    /**
     * @Param [merNo 要迁移的商户编号, agentNum 要迁移的代理商编号]
     * @Return int
     */
    @Transactional
    @Override
    public AjaxResult newMerMigrateUpdate(String merNo, String agentNum, String reachAgentNum, String actAgentNum, String flowAgentNum) {
        try {
            LogUtils.logInfo("开始迁移商户:" + merNo + "----" + "代理商编号:" + agentNum);
            //获取商户信息
            MerchantInfo merchantInfo = merchantInfoMapper.selectMerchantInfoById(merNo);
            if (merchantInfo.getMerStatus().intValue() == 1) {
                LogUtils.logInfo("当前商户已停用");
                return AjaxResult.error("当前商户已停用");
            }
            //原服务商编号
            String thisAgentNum = merchantInfo.getAgentNo();
            //原代理编号和要迁移代理不可相同
            if (agentNum.equals(thisAgentNum)) {
                LogUtils.logInfo("已经所属目标代理商,不可重复迁移");
                return AjaxResult.error("已经所属目标代理商,不可重复迁移");
            }
            //要迁移的服务商信息
            AgentInfo agentInfo = agentInfoMapper.selectAgentInfoById1(agentNum);
            //查询代理的顶级代理
            AgentInfo agentInfo3 = agentInfoMapper.selectAgentInfoByAgentNum2(agentNum);
            List<AgentInfo> agentInfo4 = agentInfoMapper.selectAgentInfoByAgentNum3(agentInfo3.getAgentNum());
            List<String> collect = agentInfo4.stream().map(AgentInfo::getAgentNum).collect(Collectors.toList());
            if (agentInfo == null) {
                LogUtils.logInfo("代理商不存在");
                return AjaxResult.error("代理商不存在");
            }
            // 0 正常代理
            if (!"0".equals(agentInfo.getAgentStatus())) {
                LogUtils.logInfo("代理商状态非正常,请先确认代理商状态");
                return AjaxResult.error("代理商状态非正常代理,请先确认代理商状态");
            }
            if (!collect.contains(thisAgentNum)) {
                LogUtils.logInfo("目标服务商非上下级,无法迁移！");
                return AjaxResult.error("目标服务商非上下级,无法迁移！");
            }

            //新商户迁移记录
            NewMerRecord newMerRecord = new NewMerRecord();
            newMerRecord.setMerNo(merNo);
            newMerRecord.setMerName(merchantInfo.getMerName());
            //设置原代理商信息
            newMerRecord.setAgentNum(thisAgentNum);
            AgentInfo agentInfo1 = agentInfoMapper.selectAgentInfoByAgentNum1(thisAgentNum);
            newMerRecord.setAgentName(agentInfo1.getAgentName());
            //设置新代理商信息
            newMerRecord.setNewAgentNum(agentNum);
            AgentInfo agentInfo2 = agentInfoMapper.selectAgentInfoByAgentNum1(agentNum);
            newMerRecord.setNewAgentName(agentInfo2.getAgentName());
            //设置SN编号
            FormalPos formalPos = null;
            String posno = "";
            String sn = "";
            if (formalPosMapper.selectFormalPosByMerNo(merNo) != null) {
                formalPos = formalPosMapper.selectFormalPosByMerNo(merNo);
                posno = formalPos.getPosno();
                sn = formalPos.getMachineNum();
            }
            //设置原激活、达标、返现对象编号,在有SN的情况下
            newMerRecord.setSn(sn);
            BranchPos branchPos = null;
            branchPos = branchPosMapper.selectBranchPosByPosno(posno);
            //是否返现
            int act = branchPosMapper.selectBranchPosByPosno1(posno);
            int reach = branchPosMapper.selectBranchPosByPosno2(posno);
            int flow = branchPosMapper.selectBranchPosByPosno3(posno);
            if (branchPos != null) {
                if (branchPos.getActAgentNum() != null) {
                    newMerRecord.setReachAgentNum(branchPos.getReachAgentNum());
                } else {
                    newMerRecord.setReachAgentNum(reachAgentNum);
                }
                if (branchPos.getReachAgentNum() != null) {
                    newMerRecord.setActAgentNum(branchPos.getActAgentNum());
                } else {
                    newMerRecord.setActAgentNum(actAgentNum);
                }
                if (branchPos.getFlowAgentNum() != null) {
                    newMerRecord.setFlowAgentNum(branchPos.getFlowAgentNum());
                } else {
                    newMerRecord.setFlowAgentNum(flowAgentNum);
                }

                if (StringUtils.isNotEmpty(actAgentNum) && act < 1) {
                    newMerRecord.setNewActAgentNum(actAgentNum);
                } else if (StringUtils.isEmpty(actAgentNum)) {
                    newMerRecord.setNewActAgentNum(actAgentNum);
                } else {
                    newMerRecord.setNewFlowAgentNum("奖励已发放");
                }
                if (StringUtils.isNotEmpty(reachAgentNum) && reach < 1) {
                    newMerRecord.setNewReachAgentNum(reachAgentNum);
                } else if (StringUtils.isEmpty(reachAgentNum)) {
                    newMerRecord.setNewActAgentNum(reachAgentNum);
                } else {
                    newMerRecord.setNewFlowAgentNum("奖励已发放");
                }
                if (StringUtils.isNotEmpty(flowAgentNum) && flow < 1) {
                    newMerRecord.setNewFlowAgentNum(flowAgentNum);
                } else if (StringUtils.isEmpty(flowAgentNum)) {
                    newMerRecord.setNewActAgentNum(flowAgentNum);
                } else {
                    newMerRecord.setNewFlowAgentNum("奖励已发放");
                }
                //修改新激活、达标、返现对象编号
                Long id = branchPos.getId();
                BranchPos branchPos1 = new BranchPos();
                branchPos1.setId(id);
                branchPos1.setAgentNum(Long.valueOf(agentNum));

                if (act > 0 && !reachAgentNum.equals(branchPos.getReachAgentNum())) {
                    return AjaxResult.error("激活奖励已发放，不允许修改！");
                }
                if (reach > 0 && !actAgentNum.equals(branchPos.getActAgentNum())) {
                    return AjaxResult.error("达标奖励已发放，不允许修改！");
                }
                if (flow > 0 && !flowAgentNum.equals(branchPos.getFlowAgentNum())) {
                    return AjaxResult.error("流量卡奖励已发放，不允许修改！");
                }
                //设置新激活、达标、返现对象编号

                if (actAgentNum != null && StringUtils.isNotEmpty(sn)) {
                    branchPos1.setActAgentNum(actAgentNum);
                } else if (StringUtils.isEmpty(sn)) {
                    return AjaxResult.error("SN编号不存在，不允许修改返现编号！");
                } else {
                    return AjaxResult.error("SN编号不存在，不允许修改返现编号！");
                }
                if (reachAgentNum != null && StringUtils.isNotEmpty(sn)) {
                    branchPos1.setReachAgentNum(reachAgentNum);
                } else if (StringUtils.isEmpty(sn)) {
                    return AjaxResult.error("SN编号不存在，不允许修改返现编号！");
                } else {
                    return AjaxResult.error("SN编号不存在，不允许修改返现编号！");
                }
                if (flowAgentNum != null && StringUtils.isNotEmpty(sn)) {
                    branchPos1.setFlowAgentNum(flowAgentNum);
                } else if (StringUtils.isEmpty(sn)) {
                    return AjaxResult.error("SN编号不存在，不允许修改返现编号！");
                } else {
                    return AjaxResult.error("SN编号不存在，不允许修改返现编号！");
                }
                branchPosMapper.updateBranchPos(branchPos1);
            }

            //设置原激活、达标、返现对象编号，在无SN的情况下
            else {
                if (act > 0) {
                    return AjaxResult.error("激活奖励已发放，不允许修改！");
                }
                if (reach > 0) {
                    return AjaxResult.error("达标奖励已发放，不允许修改！");
                }
                if (flow > 0) {
                    return AjaxResult.error("流量卡奖励已发放，不允许修改！");
                }
                if (StringUtils.isEmpty(sn) && StringUtils.isNotEmpty(reachAgentNum)) {
                    return AjaxResult.error("SN编号不存在，不允许修改返现编号！");
                }
                if (StringUtils.isEmpty(sn) && StringUtils.isNotEmpty(actAgentNum)) {
                    return AjaxResult.error("SN编号不存在，不允许修改返现编号！");
                }
                if (StringUtils.isEmpty(sn) && StringUtils.isNotEmpty(flowAgentNum)) {
                    return AjaxResult.error("SN编号不存在，不允许修改返现编号！");
                }
                newMerRecord.setReachAgentNum(reachAgentNum);
                newMerRecord.setActAgentNum(actAgentNum);
                newMerRecord.setFlowAgentNum(flowAgentNum);
                newMerRecord.setNewActAgentNum(agentNum);
                newMerRecord.setNewReachAgentNum(agentNum);
                newMerRecord.setNewFlowAgentNum(agentNum);
            }
            MerchantTotal merchantTotals = merchantTotalMapper.selectMerchantTotalByMerno(merNo);
            if (merchantTotals == null) {
                return AjaxResult.error("商户信息统计数据为空，迁移失败");
            }
            Long id = merchantTotals.getId();
            MerchantTotal merchantTotal = new MerchantTotal();
            merchantTotal.setId(id);
            merchantTotal.setMerno(merNo);
            merchantTotal.setAgentNum(agentNum);
            newMerRecord.setUpdateDate(DateUtils.getNowDate());

            merchantTotalMapper.updateMerchantTotal(merchantTotal);
            newMerRecordMapper.insertNewMerRecord(newMerRecord);
            //修改迁移信息
            MerchantInfo mer = new MerchantInfo();
            mer.setIsMigrate(1);
            mer.setOriginalAgentNum(thisAgentNum);
            mer.setAgentNo(agentNum);
            mer.setMigrateDate(DateUtils.getTime());
            mer.setMerno(merNo);
            LogUtils.logInfo("迁移参数：" + JSON.toJSONString(mer));
            int i = merchantInfoMapper.updateMerchantInfo(mer);
            if (i > 0) {
                //迁移branch_pos 和 formal_pos
                Map<String, Object> formalPos1 = merchantInfoMapper.getFormalPosByMerno(merNo);
                if (ObjectUtils.allNotNull(formalPos1)) {
                    Map<String, Object> request = new HashMap<>();
                    request.put("posno", formalPos1.get("POSNO"));
                    request.put("agentNum", agentNum);
                    i = merchantInfoMapper.updateBranchPos(request);
                    if (i > 0) {
                        i = merchantInfoMapper.updateFormalPos(request);
                    }
                }
            } else {
                LogUtils.logInfo("迁移失败:修改结果[ " + i + " ]");
                return AjaxResult.error("迁移失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.logInfo("迁移异常" + e);
            return AjaxResult.error("迁移异常");
        }
        LogUtils.logInfo("迁移成功" + merNo + "----" + "代理商编号:" + agentNum);
        return AjaxResult.success("迁移成功");
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateMerMes(Map<String, String> params, String merno, HttpServletRequest request, String createName) throws Exception {
        MerchantInfo merchantInfo1 = merchantInfoMapper.selectMerchantInfoById(merno);

        //只有正式商户才可上传图片资料
        if (0 != merchantInfo1.getMerStatus()) {
            throw new BusinessException("当前商户非正式用户");
        }
        //存储图片
        List<ClientImg> imgList = new ArrayList<>();
        //上传图片服务器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

            Iterator iter = multiRequest.getFileNames();
            boolean b = iter.hasNext();
            if (!b) {
                throw new BusinessException("图片资料不能为空");
            } else if (multiRequest.getFileMap().size() < 3) {
                throw new BusinessException("请补全图片资料");
            }
            while (b) {
                Object next = null;
                try {
                    next = iter.next();
                } catch (Exception e) {
                    break;
                }
                MultipartFile img = multiRequest.getFile(next.toString());
                if (img != null && img.getSize() != 0) {
                    //获取文件名称
                    String hou = img.getOriginalFilename();
                    //验证图片类型
                    String reg = ".+(.png|.jpg|.bmp|.jpeg)$";
                    //图片后缀类型
                    String replace = hou.toLowerCase().replaceAll(" ", "");
                    if (!Pattern.compile(reg).matcher(replace).find()) {
                        throw new BusinessException("请上传指定格式图片资料");
                    }

                    hou = hou.substring(hou.indexOf("."), hou.length());
                    //图片查看路径
                    ClientImg clientImg = new ClientImg();
                    //上传文件 到 fastdfs
                    String fileName = merno + "-" + img.getName() + hou;

                    File dfile = null;
                    try {
                        dfile = File.createTempFile("prefix", "_" + img.getOriginalFilename());
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    try {
                        img.transferTo(dfile);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    Map<String, String> metaList = new HashMap<String, String>();
                    metaList.put("fileName", fileName);
                    metaList.put("fileType", img.getName());
                    metaList.put("author", createName);
                    metaList.put("date", com.hjm.project.agentInfo.agentInfo.utils.Utils.formateDate(2));//年月日 时分秒
                    String fid = FastDFSClient.uploadFile(dfile, dfile.getName(), metaList);
                    clientImg.setFastdfsGroup("group1/M00/00/00/");
                    if (com.hjm.project.agentInfo.agentInfo.utils.Utils.IsNull(fid)) {
                        clientImg.setFileid("");
                    } else {
                        clientImg.setFileid(fid);
                    }
                    clientImg.setClientno(merno);
                    clientImg.setType(Long.parseLong(img.getName()));
                    clientImg.setCreatename(createName);
                    clientImg.setObjType(Long.parseLong("1"));
                    imgList.add(clientImg);
                }
            }
        }
        List<String> collect1 = imgList.stream().map(ClientImg::getFileid).collect(Collectors.toList());

        //发送请求
        String applyId = merchantInfo1.getApplyId();
        MerchantDto data =(MerchantDto) getMerNewchantRate(merno, applyId).get("data");
        String mchtStatus = data.getMchtStatus();
        JSONObject jsonObject = UpdateMerUtils.updateMerchant(params, merchantInfo1.getLdMerno(), merchantInfo1,collect1,mchtStatus);
        //返回推送结果，结果成功则继续
        if (!jsonObject.get("status").toString().equals("0000")){
            return AjaxResult.error(jsonObject.getString("msg"));
        }
        //修改前的数据记录
        insertOldRecord(merno);

        //修改商户法人姓名
        MerchantInfo mer = new MerchantInfo();
        mer.setMerno(params.get("merno"));
        mer.setLegalName(params.get("legal_name"));
        mer.setLegalCerno(EncryptUtils.getEncrypt(params.get("screenIdnum")));
        mer.setLinkPhone(EncryptUtils.getEncrypt(params.get("resphone")));
        mer.setShowLegalcerno(Utils.dealCard(params.get("resphone")));
        mer.setShowLinkphone(com.hjm.common.utils.Utils.dealPhone(params.get("resphone")));
        merchantInfoMapper.updateMerchantInfo(mer);

        //拼接账户信息参数
        Accounts accounts = new Accounts();
        accounts.setSeqId(params.get("merno"));
        accounts.setScreenName(params.get("screenName"));
        accounts.setScreenIdnum(EncryptUtils.getEncrypt(params.get("screenIdnum")));
        accounts.setResphone(EncryptUtils.getEncrypt(params.get("resphone")));
        accounts.setScreenNum(EncryptUtils.getEncrypt(params.get("screenNum")));
        accounts.setBankHeadname(params.get("headBank"));
        accounts.setBankName(params.get("branchBank"));
        accounts.setBankNum(params.get("subbranchId"));
        Map<String, Object> areaP = new HashMap();
        areaP.put("area_code", params.get("province"));
        areaP.put("area_type", "0");
        Map<String, Object> pMap = areaMapper.findQBAreaName(areaP);
        areaP.put("area_code", params.get("city"));
        areaP.put("area_type", "1");
        Map<String, Object> cMap = areaMapper.findQBAreaName(areaP);
        accounts.setAreaName(pMap.get("AREA_NAME") + "," + cMap.get("AREA_NAME"));
        accounts.setBankAddress(params.get("province") + "," + params.get("city"));
        accounts.setDaMarker(2);
        //修改本地账户信息
        int result = accountsMapper.updateAccountsBySeqId(accounts);

        int result1 = -1;
        //先获取服务商所有的图片服务器的地址 查看是否有图片
        ClientImg clientImg = new ClientImg();
        clientImg.setClientno(merno);
        List<ClientImg> clientImgs = clientImgMapper.selectclientImgList(clientImg);
        //存在全部删除
        //要删除的类型
        String[] types = new String[]{"1", "2", "4"};
        if (CollectionUtils.isNotEmpty(clientImgs)) {
            for (ClientImg img : clientImgs) {
                if (Arrays.asList(types).contains(img.getType().toString())) {
                    result1 = FastDFSClient.deleteFile(img.getFileid());
                    if (result1 == -1) {
                        throw new BusinessException("上传图片资料失败");
                        }
                    //清除旧图片成功后删除数据库的图片地址信息
                    result1 = clientImgMapper.deleteclientImgById(img.getId());
                    if (result1 <= 0) {
                        throw new BusinessException("上传图片资料失败");
                    }
                }
            }
        }
        for (ClientImg img : imgList) {
            result1 = clientImgMapper.insertclientImg(img);
            if (result1 <= 0) {
                throw new BusinessException("上传图片资料失败,请重新上传");
            }
        }

        if (result1 <= 0) {
            throw new BusinessException("上传图片失败,请重新上传");
        }
        if (result > 0) {
            //保修改后的数据记录
            insertNewRecord(params, imgList, collect1);
            merchantInfoMapper.updateMerchantCardBag(params);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("本地修改失败");
        }

    }




    /**
     * 修改后的数据记录
     *
     * @param params
     * @param imgList
     * @param collect1
     */
    private void insertNewRecord(Map<String, String> params, List<ClientImg> imgList, List<String> collect1) {
        MerSyncRecord merSyncRecord1 = new MerSyncRecord();
        merSyncRecord1.setBratch("2");
        merSyncRecord1.setType("2");
        merSyncRecord1.setScreenName(params.get("screenName"));
        merSyncRecord1.setScreenNum(params.get("screenNum"));
        merSyncRecord1.setBankNum(params.get("bankNum"));
        merSyncRecord1.setSeqId(params.get("merno"));
        merSyncRecord1.setScreenIdnum(params.get("screenIdnum"));
        merSyncRecord1.setResphone(params.get("resphone"));
        merSyncRecord1.setBankHeadname(params.get("headBank"));
        merSyncRecord1.setBankAddress(params.get("province") + "," + params.get("city"));
        if (imgList != null) {
            merSyncRecord1.setBankcardImg(collect1.size() > 2 ? collect1.get(2) : "");
            merSyncRecord1.setFontIdImg(collect1.size() > 0 ? collect1.get(0) : "");
            merSyncRecord1.setBackIdImg(collect1.size() > 1 ? collect1.get(1) : "");
        }
        merSyncRecord1.setUpdateDate(DateUtils.getNowDate());
        merSyncRecordMapper.insertMerSyncRecord(merSyncRecord1);
    }

    /**
     * 未修改前的数据记录
     *
     * @param merno
     * @throws Exception
     */
    private void insertOldRecord(String merno) throws Exception {
        Map<String, Object> accountsMap = accountsMapper.selectAccountsMapBySeqId(merno);
        if(accountsMap == null){
            accountsMap = new HashMap<>();
        }
        List<ClientImg> clientImg1 = clientImgMapper.selectclientImgByClientNo(merno);
        MerSyncRecord merSyncRecord = new MerSyncRecord();
        merSyncRecord.setBratch("1");
        merSyncRecord.setType("1");
        merSyncRecord.setScreenName((String) accountsMap.get("SCREEN_NAME"));
        merSyncRecord.setScreenNum(accountsMap.get("SCREEN_NUM") != null ? EncryptUtils.getDecrypt((String) accountsMap.get("SCREEN_NUM")) : "");
        merSyncRecord.setBankNum((String) accountsMap.get("BANK_NUM"));
        merSyncRecord.setSeqId((String) accountsMap.get("SEQ_ID"));
        merSyncRecord.setScreenIdnum(accountsMap.get("SCREEN_IDNUM") != null ? EncryptUtils.getDecrypt((String) accountsMap.get("SCREEN_IDNUM")) : "");
        merSyncRecord.setResphone(accountsMap.get("RESPHONE") != null ? EncryptUtils.getDecrypt((String) accountsMap.get("RESPHONE")) : "");
        merSyncRecord.setBankHeadname((String) accountsMap.get("BANK_HEADNAME"));
        merSyncRecord.setBankAddress((String) accountsMap.get("BANK_ADDRESS"));
        if (clientImg1 != null) {
            List<String> collect = clientImg1.stream().map(ClientImg::getFileid).collect(Collectors.toList());
            merSyncRecord.setBankcardImg(collect.size() > 2 ? collect.get(2) : "");
            merSyncRecord.setFontIdImg(collect.size() > 0 ? collect.get(0) : "");
            merSyncRecord.setBackIdImg(collect.size() > 1 ? collect.get(1) : "");
        }
        merSyncRecord.setUpdateDate(DateUtils.getNowDate());
        merSyncRecordMapper.insertMerSyncRecord(merSyncRecord);
    }

    @Override
    public List<MerUpdateAreaRecord> selectMerUpdateAreaRecordList(MerUpdateAreaRecord merUpdateAreaRecord){
        return merchantInfoMapper.selectMerUpdateAreaRecordList(merUpdateAreaRecord);
    }

    @Override
    public List<Map<String,Object>> allProblemList(Map param)throws Exception{
        return merchantInfoMapper.allProblemList(param);
    }

    @Override
    public Map<String,Object> updateProblemStatus(String merno, Integer status, Integer type, Integer mer_status)throws Exception{
        Map<String,Object> resultMap=new HashMap<>();
        int result=0;
        Map params = new HashMap();
        params.put("merno", merno);
        params.put("status", status);
        Map<String,Object> merMap=merchantInfoMapper.getSettleCycle(params);
        if (status==2){
            if (type==0){
                params.put("mer_status",mer_status);
                result=merchantInfoMapper.updateMerchantInfoRepulse(params);
                if (result>0){
                    merchantInfoMapper.updateProblemStatus(params);
                }
            }else if (type==1){
                params.put("mer_status",mer_status);
                result=merchantInfoMapper.updateMerchantInfoRepulse(params);
                if (result>0){
                    merchantInfoMapper.updateProblemStatus(params);
                }
            }

        }else if (status==1){
            if (type==0){
                result=merchantInfoMapper.updateProblemStatus(params);
            }else if (type==1){
                if (Integer.parseInt(merMap.get("EXAMINE").toString())==1){
                    //人工审核提交钱宝修改
                    Map<String,String> map=setMerchantImg(merno);
                    if (map.get("code").equals("200")){
                        params.put("mer_status",0);
                        result=merchantInfoMapper.updateMerchantInfo1(params);
                        resultMap.put("result",result);
                        return resultMap;
                    }else {
                        resultMap.put("result",0);
                        resultMap.put("msg",map.get("msg"));
                        return resultMap;
                    }
                }else if (Integer.parseInt(merMap.get("EXAMINE").toString())==2){
                    //人工审核提交钱宝进件
                    Map<String,String> map=addRegisterMem(merno, "总后台管理员");
                    if (map.get("code").equals("200")){
                        resultMap.put("result",1);
                        return resultMap;
                    }else {
                        resultMap.put("result",0);
                        resultMap.put("msg",map.get("msg"));
                        return resultMap;
                    }
                }
            }
        }
        resultMap.put("result",result);
        if (result==0){
            resultMap.put("msg","操作失败");
        }
        return resultMap;
    }


    /**
     * 人工审核提交钱宝修改
     * @param merNo
     * @return
     */
    public Map<String,String> setMerchantImg(String merNo) {
        Map<String,String> result=new HashMap<>(16);
        result.put("code","200");
        result.put("msg","成功");
        Map<String,Object> merchantInfoObj = merchantInfoMapper.getMapMer(merNo);
        Map<String,String> merchantInfo=new HashMap<>(64);
        merchantInfoObj.forEach((k,v)->{
            merchantInfo.put(k,String.valueOf(v));
        });
        StringBuffer log = new StringBuffer();
        try{
            Map<String, String> requestMap = new HashMap<>();
            //商户资料
            Map<String, String> reqMap = new HashMap<>();
            reqMap.put("originalMid",merNo);
            reqMap.put("mchtNo", merchantInfo.get("LD_MERNO"));//钱宝商户编号
            //法人证件有效日期 格式：yyyyMMdd ,长期有效填“21991231”
            String certExpdate = merchantInfo.get("LEGAL_DATE").replace("-","");
            certExpdate = certExpdate.replace(certExpdate.substring(0,8),"");
            reqMap.put("certExpdate", "长期".equals(certExpdate) ? "21991231" : certExpdate);
            //图片资料
            Map<String,Object> imgMap = new HashMap<>();
            imgMap.put("clientno",merNo);
            imgMap.put("obj_type","0");
            List<Map<String,Object>> imgList = merchantInfoMapper.imgList(imgMap);
            Map<String, String> fileMap = new HashMap<>();
            Map<String, String> cardMap = new HashMap<>();
            String cImgurl="http://10.71.11.13/";
            for (Map<String,Object> clientImg : imgList) {
                int cleientType=Integer.parseInt(String.valueOf(clientImg.get("TYPE")));
                String fileid=String.valueOf(clientImg.get("FILEID"));
                if ((cleientType == 1 || cleientType == 2 || cleientType == 3 || cleientType == 29 || cleientType == 30 || cleientType == 39)) {//证件照照片
                    fileMap.put(merNo + "_zjz" + cleientType + ".jpg", cImgurl + fileid);
                }
                if ((cleientType == 38 || cleientType == 4 || cleientType == 18)) {//结算卡照片
                    cardMap.put(merNo + "_jsk" + cleientType + ".jpg", cImgurl + fileid);
                }
            }
            Map<String, Map<String, String>> imageMap = new HashMap<>();
            imageMap.put("upload3",fileMap);
            imageMap.put("upload10",cardMap);
            //报文主体
            requestMap.put("source", "2B");//商户来源
            requestMap.put("busType","1");
            requestMap.put("merchantInfo", JSONObject.toJSONString(reqMap));
            requestMap.put("fileDate", JSONObject.toJSONString(imageMap));

            //发送请求
            String s1 = JSONObject.toJSONString(requestMap);
            //log.append("商户修改证件照片请求，请求时间："+DateUtils.getYmdHsmS()+"，请求内容："+s1+"\r\n");
            JSONObject jsonObject = HttpClientUtils.sendHttpPostJson(AutoLoadData.qbMerUpdateUrl, s1);
            //log.append("商户修改证件照片响应，响应时间："+DateUtils.getYmdHsmS()+"，响应内容："+str+"\r\n");
            //esLogger.info(log.toString());

            Map jsonMap = JSONObject.parseObject(String.valueOf(jsonObject), Map.class);
            if ("200".equals(String.valueOf(jsonMap.get("responseCode")))) {
                Map successMap = JSONObject.parseObject(String.valueOf(jsonMap.get("responseVal")), Map.class);
                if(!"A10".equals(successMap.get("code").toString())){
                    if("A13".equals(successMap.get("code").toString())){
                        result.put("code","500");
                        result.put("msg","上游接口异常!");
                        return result;
                    }else if("A15".equals(successMap.get("code").toString())){
                        result.put("code","500");
                        result.put("msg","商户信息异常，请联系客服！"+"["+successMap.get("message")+"]");
                        return result;
                    }else{
                        result.put("code","500");
                        result.put("msg","提交审核失败，请稍后再试！");
                        return result;
                    }
                }else{
                    return  result;
                }
            }else{
                result.put("code","500");
                result.put("msg","请求上游接口失败！");
                return result;
            }

        }catch (Exception e){
            throw e;
        }

    }

    /**
     * 人工审核提交钱宝进件
     * @param merno
     * @param addMan
     * @return
     * @throws Exception
     */
    public Map<String,String> addRegisterMem(String merno,String addMan) throws Exception{
        Map<String,String> result=new HashMap<>(16);
        result.put("code","200");
        result.put("msg","成功");
        Map reqNap = new HashMap();
        StringBuffer log = new StringBuffer();
        try {
            //企业信息
            Map<String,Object> merchantScheduleObj = merchantInfoMapper.getMerInfoExpand(merno);
            Map<String,String> merchantSchedule=new HashMap<>(64);
            merchantScheduleObj.forEach((k,v)->{
                merchantSchedule.put(k,String.valueOf(v));
            });
            //账户资料
            Map<String,Object> accountsParmas = new HashMap<>();
            accountsParmas.put("seq_id",merno);
            accountsParmas.put("type",Short.valueOf("2"));
            Map<String,String> accounts = new HashMap<>(64);
            accountsParmas = merchantInfoMapper.getOneMap(accountsParmas);
            accountsParmas.forEach((k,v)->{
                accounts.put(k,String.valueOf(v));
            });
            //图片资料
            Map<String,Object> imgMap = new HashMap<>();
            imgMap.put("clientno",merno);
            imgMap.put("obj_type","0");
            List<Map<String,Object>> imgList = merchantInfoMapper.imgList(imgMap);

            Map<String, String> reqMap = new HashMap<>();
            //商户号
            reqMap.put("originalMid", merchantSchedule.get("MERNO"));
            String type = "2";
            //商户类型 01-公司商户，02-个体商，03-无营业执照商户
            String merType=merchantSchedule.get("MER_TYPE");
            String merNature=merchantSchedule.get("MER_NATURE");
            if (("5".equals(merType) && "1".equals(merNature)) || ("0".equals(merType) && "1".equals(merNature))) {
                reqMap.put("mchtType", "03");
                //约定业务 0-经营类，1-收款类，2-经营收款类
                reqMap.put("busType", "1");
            } else {
                type = "1";
                reqMap.put("mchtType", "01");
                //约定业务 0-经营类，1-收款类，2-经营收款类
                reqMap.put("busType", "0");
            }
            //商户全称
            reqMap.put("mchtNm", toChar(merchantSchedule.get("MER_SHORTNAME")));
            //商户简称
            String merName=merchantSchedule.get("MER_NAME");
            reqMap.put("mchtCnAbbr",toChar(merName.length()>12 ? merName.substring(0,11) : merName));
            if ("1".equals(type)) {
                //商户注册地址 公司商户、个体商户时必填
                reqMap.put("compaddr", toChar(merchantSchedule.get("SHOP_ADDRESS")));
                //注册资本  公司商户、个体商户时必填，单位元，正整数  -----
                Integer registeredCapital=Integer.parseInt(merchantSchedule.get("REGISTERED_CAPITAL"));
                reqMap.put("busAmt", df.format( registeredCapital* 10000));
                //营业执照号码 公司商户、个体商户时必填  ------
                String socialReditCode=merchantSchedule.get("SOCIAL_REDIT_CODE");
                reqMap.put("licenceNo", socialReditCode);
                //营业执照有效期 公司商户、个体商户时必填，格式：yyyyMMdd  ------
                String srcEndDate=merchantSchedule.get("SRC_END_DATE");
                reqMap.put("licenceEndDate","长期".equals(srcEndDate) ? "21991231" : srcEndDate.replace("-",""));
                //税务登记证号码 公司商户、个体商户时必填  ------
                reqMap.put("taxNo", socialReditCode);
            }

            //法人代表
            reqMap.put("manager", merchantSchedule.get("LEGAL_NAME"));
            //法人有效证件种类  01身份证
            reqMap.put("certType", "01");
            //法人有效证件号码
            reqMap.put("certNo", EncryptUtils.getDecrypt(merchantSchedule.get("LEGAL_CERNO")));
            //法人证件有效日期 格式：yyyyMMdd ,长期有效填“21991231”
            String certExpdate = merchantSchedule.get("LEGAL_DATE").split("-")[1];
            reqMap.put("certExpdate", "长期".equals(certExpdate) ? "21991231" : certExpdate);
            //经营明细 经营类，经营收款类必传  参考经营明细表RELATION_ID 如：酒店/宾馆住宿，则取值010002  -------
            reqMap.put("operNo", merchantSchedule.get("MCC_NUM"));
            //有关系商户数  约定业务为收款类时，有关系商户数不可为空！
            reqMap.put("openDays", "1");
            //省市区
            String[] mer = merchantSchedule.get("MER_CODE").split(",");
            //装机地址-省/直辖市 北京市  -------
            reqMap.put("addrProvince", mer[0]);
            //装机地址-市 北京市  -------
            reqMap.put("addrCity", mer[1]);
            //装机地址-县/区 东城区  -------
            reqMap.put("addrCounty", mer[2]);
            //装机地址-详细地址  -------
            reqMap.put("addr", (StringUtil.isEmpty(merchantSchedule.get("MER_DETAILED_ADDRESS")) || "未获取到位置".equals(merchantSchedule.get("MER_DETAILED_ADDRESS"))) ? toChar(merchantSchedule.get("MER_ADDRESS")) : toChar(merchantSchedule.get("MER_DETAILED_ADDRESS")));
            //商户联系人
            reqMap.put("contact", merchantSchedule.get("LINK_MAN"));
            //联系手机
            reqMap.put("commTel", EncryptUtils.getDecrypt(accounts.get("RESPHONE")));
            //结算账户类型 0-对公账户，1-对私账户
            if ("1".equals(accounts.get("NATURE"))) {
                reqMap.put("clearType", "0");
            } else {
                reqMap.put("clearType", "1");
            }
            //开账户户名
            reqMap.put("settleAcctNm", accounts.get("SCREEN_NAME"));
            //账户号
            reqMap.put("settleAcctNo", EncryptUtils.getDecrypt(accounts.get("SCREEN_NUM")));
            //银行预留手机号
            reqMap.put("settleBindTel", EncryptUtils.getDecrypt(accounts.get("RESPHONE")));
            //开户支行全称
            reqMap.put("settleBankNm", accounts.get("BANK_NAME"));
            //支行号
            reqMap.put("bankBranchNo", accounts.get("BANK_NUM"));
            //结算类型 0-T+N
            reqMap.put("settlTp", "0");
            //T+N 0-T+0，1-T+1
            reqMap.put("settlTN", "0");
            //是否开通商城功能 0-否，1-是；1.分润扣率为标准扣率时才允许开通商城功能；2.T1商户暂不开通商城消费；3.合作伙伴未开通商城消费，商户不能开通商城消费
            reqMap.put("openMall", "1");
            //手续费方式 1-比例+封顶
            reqMap.put("feeType", "1");

            Map<String,Object> merchantInfoObj = merchantInfoMapper.getMapMer(merno);
            Map<String,String> merchantInfo=new HashMap<>(64);
            merchantInfoObj.forEach((k,v)->{
                merchantInfo.put(k,String.valueOf(v));
            });
            //商户类型的进件添加费率
            if (Integer.parseInt(merchantInfo.get("APP_TYPE").toString())==2) {
                //获取附加费率
                List<Map<String,Object>> getFuJiaList = merchantInfoMapper.getFuJiaInFo();
                //获取垫资费率
                List<Map<String,Object>> getDianZiList = merchantInfoMapper.getDianZiInFo();
                //获取费率信息
                List<Map<String,Object>> getFeiLvList = merchantInfoMapper.getFeiLvInFo();
                for (Map<String,Object> feiLv : getFeiLvList) {
                    Map<String,Object> merchantRate = new HashMap<>();
                    merchantRate.put("merno",merno);
                    merchantRate.put("settle_type",Integer.parseInt(String.valueOf(feiLv.get("SETTLE_TYPE"))));
                    merchantRate.put("card_type",Integer.parseInt(String.valueOf(feiLv.get("CARDTYPE"))));
                    String msgType = "";
                    if ("0".equals(feiLv.get("RATETYPE")) || "6".equals(feiLv.get("RATETYPE"))) {
                        msgType = "H007";
                    } else if ("1".equals(feiLv.get("RATETYPE"))) {
                        msgType = "H007";
                    } else if ("2".equals(feiLv.get("RATETYPE"))) {
                        msgType = "H202";
                    } else if ("3".equals(feiLv.get("RATETYPE"))) {
                        msgType = "H201";
                    } else if ("4".equals(feiLv.get("RATETYPE"))) {
                        msgType = "H302";
                    }
                    //商户类别(0-标准类、1-优惠类、2-减免类、3-电签会员)
                    if ("6".equals(feiLv.get("RATETYPE"))) {
                        merchantRate.put("mer_category",3);
                        merchantRate.put("rate_type",0);
                    } else {
                        merchantRate.put("mer_category",0);
                        merchantRate.put("rate_type",Integer.parseInt(String.valueOf(feiLv.get("RATETYPE"))));
                    }
                    merchantRate.put("msgtype",msgType);
                    merchantRate.put("rate_code",feiLv.get("AR_MARK"));
                    if (getFuJiaList.size() > 0) {
                        merchantRate.put("rate_affix",getFuJiaList.get(0).get("AR_MARK"));
                    }
                    if (getDianZiList.size() > 0) {
                        merchantRate.put("rate_dz",getDianZiList.get(0).get("AR_MARK"));
                    }
                    merchantRate.put("add_man",addMan);
                    merchantRate.put("add_date",Utils.formateDate(0));
                    merchantRate.put("add_time",Utils.formateDate(3));
                    merchantInfoMapper.addMerchantRate(merchantRate);
                }
            }
            //费率信息
            Map<String,Object> merRateObj = merchantInfoMapper.getMerchantRateInfo(merno);
            if (org.apache.commons.collections4.MapUtils.isEmpty(merRateObj)) {
                merRateObj = new HashMap<>();
            }
            Map<String,String> merRate=new HashMap<>(32);
            merRateObj.forEach((k,v)->{
                merRate.put(k,String.valueOf(v));
            });
            //借记卡-比例 单位%，保留2位小数 ，正数
            if (merRate != null && !org.springframework.util.StringUtils.isEmpty(merRate.get("JFL"))) {
                reqMap.put("dcRate", df.format(Double.valueOf(merRate.get("JFL").replace("%", ""))));
                reqMap.put("emporiumPreferenceDebitFee",df.format(Double.valueOf(merRate.get("JFL").replace("%", ""))));
            } else {
                reqMap.put("dcRate", "0.55");
                reqMap.put("emporiumPreferenceDebitFee","0.55");
            }
            //借记卡-封顶 单位：元 ，保留2位小数，整数部分最大三位，正数或-1（-1表示不封顶）
            if (merRate != null && !org.springframework.util.StringUtils.isEmpty(merRate.get("JFD")) && Integer.parseInt(merRate.get("JFD")) > 0) {
                reqMap.put("dcMax", df.format(Integer.parseInt(merRate.get("JFD"))));
                reqMap.put("emporiumPreferenceDebitAmt",df.format(Integer.parseInt(merRate.get("JFD"))));
            } else {
                reqMap.put("dcMax", "-1");
                reqMap.put("emporiumPreferenceDebitAmt","-1");
            }
            //贷记卡-比例 单位%，保留2位小数，正数
            if (merRate != null && !org.springframework.util.StringUtils.isEmpty(merRate.get("DFL"))) {
                reqMap.put("ccRate", df.format(Double.valueOf(merRate.get("DFL").replace("%", ""))));
                reqMap.put("emporiumPreferenceCreditFee",df.format(Double.valueOf(merRate.get("DFL").replace("%", ""))));
            } else {
                reqMap.put("ccRate", "0.55");
                reqMap.put("emporiumPreferenceCreditFee","0.55");
            }
            //贷记卡-封顶 单位：元 ，至少保留2位小数，整数部分最大三位，正数或-1（-1表示不封顶），目前只可填-1
//            if(merRate!=null && !StringUtils.isEmpty(merRate.getDfd()) && !"0".equals(merRate.getDfd())){
//                reqMap.put("ccMax",df.format(Integer.parseInt(merRate.getDfd())));
//            }else{
            reqMap.put("ccMax", "-1");
//            }
            //云闪付借记卡费率
            if (merRate != null && !org.springframework.util.StringUtils.isEmpty(merRate.get("YJFL"))) {
                reqMap.put("feeRateDNfc", df.format(Double.valueOf(merRate.get("YJFL").replace("%", ""))));
            } else {
                reqMap.put("feeRateDNfc", "0.38");
            }
            //云闪付贷记卡费率
            if (merRate != null && !org.springframework.util.StringUtils.isEmpty(merRate.get("YDFL"))) {
                reqMap.put("feeRateCNfc", df.format(Double.valueOf(merRate.get("YDFL").replace("%", ""))));
            } else {
                reqMap.put("feeRateCNfc", "0.38");
            }
            //扫码付业务开通：微信支付宝-被扫
            reqMap.put("alipaySweptFlag", "1");
            //微信支付宝费率
            if (merRate != null && !org.springframework.util.StringUtils.isEmpty(merRate.get("WZFL"))) {
                reqMap.put("alipayFee", df.format(Double.valueOf(merRate.get("WZFL").replace("%", ""))));
            } else {
                reqMap.put("alipayFee", "0.38");
            }
            //扫码付业务开通：银联二维码-被扫
            reqMap.put("unionQrcodeSweptFlag", "1");
            //银联二维码借记卡结算费率
            if (merRate != null && !org.springframework.util.StringUtils.isEmpty(merRate.get("EJF"))) {
                reqMap.put("unionQrcodeDebitFee", df.format(Double.valueOf(merRate.get("EJF").replace("%", ""))));
            } else {
                reqMap.put("unionQrcodeDebitFee", "0.38");
            }
            //银联二维码借记卡封顶
            if (merRate != null && !org.springframework.util.StringUtils.isEmpty(merRate.get("EJFD")) && !"0".equals(merRate.get("EJFD"))) {
                reqMap.put("unionQrcodeDebitAmt", df.format(Integer.parseInt(merRate.get("EJFD"))));
            } else {
                reqMap.put("unionQrcodeDebitAmt", "-1");
            }
            //银联二维码贷记卡结算费率
            if (merRate != null && !org.springframework.util.StringUtils.isEmpty(merRate.get("EDF"))) {
                reqMap.put("unionQrcodeCreditFee", df.format(Double.valueOf(merRate.get("EDF").replace("%", ""))));
            } else {
                reqMap.put("unionQrcodeCreditFee", "0.38");
            }
            //有关系商户数
            reqMap.put("openDays", "0");
            //银联国际卡费率 单位%，保留2位小数 ，正数
            reqMap.put("changeStlno", "0.55");
            //是否开通外卡受理功能 0-是；1-否; 仅T1商户可开通
            reqMap.put("wildCard", "1");
            //分润扣率代码 取合作伙伴开通的费率，钱宝全部扣率说明见附录
            reqMap.put("speSettleTp", "01");
            //是否开通提现 0-否，1-是；对私账户必输；T0只能选是；
            reqMap.put("cashFlag", "1");
            //商户提现方式 1-主动按金额，2-单笔自动；开通提现时必选；T1商户只能选择主动按金额；
            reqMap.put("cashTp", "2");
            //提现方式为满额自动是必须设置，取值范围：1000~10000
            reqMap.put("fullThreshold", "10.00");

            //提现手续费方式 1-按比例，2-单笔固定金额；开通提现时必选；
            reqMap.put("cashFeeTp", "2");
            //垫资日息(%) 正数，整数最大3位，保留3位小数；开通提现以及提现手续费方式按比例时必选；·
            if("1".equals(accounts.get("NATURE"))){//对公账户结算
                reqMap.put("cashFeeInvstIntrst","0.010");
            }else{
                if(merRate!=null && !org.springframework.util.StringUtils.isEmpty(merRate.get("DZ"))){
                    reqMap.put("cashFeeInvstIntrst",df3.format(Double.valueOf(merRate.get("DZ").replace("%",""))));
                }else{
                    reqMap.put("cashFeeInvstIntrst","0.000");
                }
            }
            //提现服务费(元)
            if (merRate != null && !org.springframework.util.StringUtils.isEmpty(merRate.get("FJ"))) {
                reqMap.put("cashFeeAmt", df.format(Integer.parseInt(merRate.get("FJ"))));
            } else {
                reqMap.put("cashFeeAmt", "0.00");
            }
            //是否开通VIP套餐 1-是，0-否
            reqMap.put("flowPackage", "0");
            //是否合规资料 0-是，1-否
            reqMap.put("compliance", "0");
            //商户MCC
            reqMap.put("mcc", merchantSchedule.get("IND_MCC"));
            //是否开通小额免签免密 0-是，1-否
            reqMap.put("freeSign", "0");
            //对账单名称（必须包含商户名称mchtNm）
            reqMap.put("statementName", merchantSchedule.get("MER_NAME") + "对账单");
            Map<String, String> terminalMap = new HashMap<>();
            //0	普通POS、1云闪付POS 、2	签约POS 、3	电话POS 、4	MISPOS 、5	移动POS 、6	网络POS 、7	MPOS 、8智能POS 、9	微POS
            terminalMap.put("posType", "0");
            //图片类型-1 机构压缩包1-身份证正面 2-身份证反面 3-手持身份证 4-结算卡正面 5-营业执照 6-店面场景 7-店面门脸 8-店铺收银
            //9-租赁合同 10-收款签名 11-代理商协议 12-活体照片 13-调单文件 14-税务登记证 15-组织机构代码证 16-开户许可证 17-代理商情况说明表 18-结算卡反面
            //19-商户协议照片-1 20-商户协议照片-2 21-商户协议照片-3 29-结算人身份证正面 30-结算人身份证反面 31-非法人结算证明文件 32-企业变更费率图片 33-企业授权个人结算书 34-其他照片
            //35 积分兑彩渠道商开户凭证 36 积分兑彩渠道商入网申请表 37 代理调价变更单 38-手持结算卡 39-结算人手持身份证 40-商户登记审核表
            Map<String, Map<String, String>> imageMap = new HashMap<>();
            String cImgurl="http://10.71.11.13/";
            String imgUrl = cImgurl +"group1/M00/00/02/CkcLDV8qIfGAJ3c_AAGMieVUGCc764.jpg";
            for (String str : folderArray) {
                Map<String, String> fileMap = new HashMap<>();
                for (Map<String,Object> clientImg : imgList) {
                    int cleientType=Integer.parseInt(String.valueOf(clientImg.get("TYPE")));
                    String fileid=String.valueOf(clientImg.get("FILEID"));
                    if (str.equals("upload") && cleientType==34) {
                        fileMap.put(merno + "_qt" + cleientType + ".jpg", cImgurl + fileid);
                    } else if (str.equals("upload1") && cleientType == 5) {//营业执照
                        fileMap.put(merno + "_yyzz.jpg", cImgurl + fileid);
                    } else if (str.equals("upload2") && cleientType == 14) {//税务登记证照片
                        fileMap.put(merno + "_swdj.jpg", cImgurl + fileid);
                    } else if (str.equals("upload3") && (cleientType == 1 || cleientType == 2 || cleientType == 29 || cleientType == 30)) {//证件照照片
                        if(cleientType == 1){
                            imgUrl=cImgurl + fileid;
                            fileMap.put(merno + "_zjz38.jpg", cImgurl + fileid);
                            fileMap.put(merno + "_zjz3.jpg", cImgurl + fileid);
                        }
                        fileMap.put(merno + "_zjz" + cleientType+ ".jpg", cImgurl + fileid);
                    } else if (str.equals("upload4") && (cleientType == 6 || cleientType == 7 || cleientType == 8)) {//门店照照片
                        fileMap.put(merno + "_mddz" + cleientType + ".jpg", cImgurl + fileid);
                    } else if (str.equals("upload5") && (cleientType == 19 || cleientType == 40)) {//商户登记审核表照片、签约协议照照片
                        if (cleientType == 19) {//签约协议照照片
                            fileMap.put(merno + "_qyxy_.jpg", cImgurl + fileid);
                        } else if (cleientType == 40) {//商户登记审核表
                            fileMap.put(merno + "_djshb_.jpg", cImgurl + fileid);
                        }
                    } else if (str.equals("upload6") && cleientType == 15) {//组织机构代码照片
                        fileMap.put(merno + "_zzjg.jpg", cImgurl + fileid);
                    } else if (str.equals("upload7") && (cleientType == 31 || cleientType == 33)) {//委托入款授权照片
                        fileMap.put(merno + "_wtsq" + cleientType + ".jpg", cImgurl + fileid);
                    } else if (str.equals("upload8")) {//房屋租赁协议照片
                    } else if (str.equals("upload10") && (cleientType == 4 || cleientType == 18 || cleientType == 16)) {//银行卡或开户许可证照片
                        if(cleientType == 4){//手持照片
                            fileMap.put(merno + "_jsk38.jpg", imgUrl);
                            fileMap.put(merno + "_jsk" + cleientType + ".jpg", cImgurl + fileid);
                        }else{
                            fileMap.put(merno + "_jsk" + cleientType + ".jpg", cImgurl + fileid);
                        }
                    } else if (str.equals("upload12")) {//小额免签免密业务申请表照片
                    } else if (str.equals("upload13") && cleientType == 17) {//商户情况说明照片
                        fileMap.put(merno + "_dlqksm" + cleientType + ".jpg", cImgurl + fileid);
                    } else if (str.equals("upload25")) {
                    }
                }
                imageMap.put(str, fileMap);
            }
            Map<String, String> requestMap = new HashMap<>();
            //商户信息
            requestMap.put("merchantInfo", JSONObject.toJSONString(reqMap));
            //机器信息
            requestMap.put("terminalInfo", JSONObject.toJSONString(terminalMap));
            //图片信息
            requestMap.put("fileDate", JSONObject.toJSONString(imageMap));
            requestMap.put("source", "2B");
            requestMap.put("type","1");
            String s1 = JSONObject.toJSONString(requestMap);

            //log.append("商户进件请求，请求时间："+DateUtils.getYmdHsmS()+"请求内容："+s1+"\r\n");
            JSONObject jsonObject = HttpClientUtils.sendHttpPostJson(AutoLoadData.qbMerUrl, s1);
            //log.append("商户进件响应，响应时间："+DateUtils.getYmdHsmS()+"，响应内容："+str+"\r\n");
            //esLogger.info(log.toString());
            Map jsonMap = JSONObject.parseObject(String.valueOf(jsonObject), Map.class);

            if ("200".equals(String.valueOf(jsonMap.get("responseCode")))){
                Map successMap=JSONObject.parseObject(String.valueOf(jsonMap.get("responseVal")), Map.class);
                if ("A10".equals(successMap.get("code").toString())) {
                    reqNap.put("status", "2");
                    Map<String,Object> merchant = new HashMap<>(16);
                    merchant.put("merno",merno);
                    merchant.put("apply_id",successMap.get("message").toString());
                    //获取到进件单号后，记录单号
                    merchantInfoMapper.updateMerchantByMerNo(merchant);
                    return result;
                }
                if ("A13".equals(successMap.get("code").toString())) {
                    result.put("code","500");
                    result.put("msg","上游接口异常!");
                    return result;
                }
                if ("A15".equals(successMap.get("code").toString())) {
                    result.put("code","500");
                    result.put("msg","商户信息异常，请联系客服！"+"["+successMap.get("message")+"]");
                    return result;
                } else {
                    result.put("code","500");
                    result.put("msg","提交审核失败，请稍后再试！");
                    return result;
                }
            }else{
                result.put("code","500");
                result.put("msg","请求上游接口失败！");
                return result;
            }

        }catch(Exception e){
            throw e;
        }
    }

    public int updateMerForProblem(String merno){
        return merchantInfoMapper.updateMerForProblem(merno);
    }

    @Override
    public AjaxResult updateMerStr(String merno) throws Exception{
        MerchantInfo mer = merchantInfoMapper.selectMerchantInfoById(merno);
        if(mer.getLdMerno() == null || mer.getApplyId() == null){
            return AjaxResult.error("商户无上游信息，无法变更");
        }
        JSONObject merchantJson = UpstreamMerInfo.getMerchant(mer.getLdMerno(), mer.getApplyId(), AutoLoadData.qbGetmerInfo);
        if (merchantJson == null) {
            return AjaxResult.error("上游接口返回为空");
        }
        //接口的请求状态
        if (!"200".equals(merchantJson.getString("responseCode"))) {
            return AjaxResult.error("接口请求失败:" + merchantJson.getString("responseCode"));
        }
        //json内层数据(上游封装结果)
        Map<String, String> map = JSONObject.parseObject(merchantJson.getString("responseVal"), Map.class);
        if (org.apache.commons.collections4.MapUtils.isEmpty(map)) {
            return AjaxResult.error("接口返回数据为空");
        }
        //上游处理结果
        if (!"A10".equals(map.get("code"))) {
            return AjaxResult.error("上游处理数据失败,错误编号:" + map.get("code"));
        }
        //内层
        Map<String, Object> data = JSONObject.parseObject(map.get("message"), Map.class);
        if (!"OK".equals(data.get("msg"))) {
            return AjaxResult.error("数据错误:" + data.get("msg"));
        }
        String merchantInfo = JSONObject.toJSONString(data.get("merchantInfo"));
        MerchantDto merchantDto = JSONObject.parseObject(merchantInfo, MerchantDto.class);
        merchantDto.setSettleAcctNo(Utils.hiddenCard(merchantDto.getSettleAcctNo()));
        merchantDto.setSettleBindTel(Utils.phone(merchantDto.getSettleBindTel()));
        merchantDto.setCommTel(Utils.phone(merchantDto.getCommTel()));
        MerchantDto result = new BeanClassUtils<MerchantDto>().setDefaultValue(merchantDto);
        if(result.getMchtStatus() != null && result.getMchtStatus().equals("0")){
            merchantInfoMapper.updateMerchantStatus(merno);
            return AjaxResult.success("变更成功");
        }else{
            return AjaxResult.error("商户上游状态不正常，无法变更");
        }
    }


    /**
     * 同步重庆商户信息
     *
     * @param data
     * @Param [body]
     * @Return com.hjm.framework.web.domain.AjaxResult
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult syncQcfMerInfo(JSONObject data) {
        String key = "016F368C0EFFD4F7E0630A00D40A67CA";
        QcfMerchantInfoVo merchantInfoVo = null;
        QcfFormalPosVo formalPosVo = null;
        String reqBody = data.getString("data");
        //解密结果
        String decrypt = AesUtils.decrypt(reqBody, key);
        try {
            JSONObject result = JSONObject.parseObject(decrypt);
            //转换商户基本信息
            merchantInfoVo = new DataConvertor<QcfMerchantInfoVo>() {
            }.format(result);
            merchantInfoVo.setMerTb(3);
            //转换商户终端信息
            formalPosVo = new DataConvertor<QcfFormalPosVo>() {
            }.format(result);
            formalPosVo.setCreatedate(DateUtils.parseDate(result.get("bindDate")));
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }

        LogUtils.logInfo("开始进行同步钱创付数据");
        LogUtils.logInfo("请求同步钱创付数据:" + decrypt);


        String posno = "";
        //查看当前终端是否入库
        TerminalLibrary ti = new TerminalLibrary();
        ti.setMachineNum(formalPosVo.getMachineNum());
        String posType = "-1";
        List<TerminalLibrary> terminalLibraries = terminalLibraryMapper.selectTerminalLibraryList(ti);
        if (CollectionUtils.isNotEmpty(terminalLibraries)) {
            posno = terminalLibraries.get(0).getPosno();
            posType = terminalLibraries.get(0).getType().toString();
        } else {
            //生成一个posno编号
            posno = terminalLibraryMapper.getPosNo().toString();
        }
        formalPosVo.setPosno(posno);
        formalPosVo.setStatus(0);

        //查看终端是否分配
        BranchPos querSn = new BranchPos();
        querSn.setMachineNum(formalPosVo.getMachineNum());
        List<BranchPos> branchPosList = branchPosMapper.selectBranchPosList(querSn);
        if (CollectionUtils.isNotEmpty(branchPosList)) {
            formalPosVo.setAgentNum(Integer.parseInt(branchPosList.get(0).getAgentNum().toString()));
            merchantInfoVo.setAgentNo(branchPosList.get(0).getAgentNum().toString());
        }
        try {
            //查看是否同步
            MerchantInfo mi = new MerchantInfo();
            mi.setLdMerno(merchantInfoVo.getLdMerno());
            List<MerchantInfo> merList = merchantInfoMapper.selectMerchantInfoList(mi);
            //查看终端是否存在
            FormalPos fpResult = formalPosMapper.selectFormalPosBySn(formalPosVo.getMachineNum());
            String merNo = "";
            int row = -1;
            MerchantInfoVo newMerchant = new MerchantInfoVo();
            if (CollectionUtils.isEmpty(merList)) {
                LogUtils.logInfo("新增同步:" + merchantInfoVo.getLdMerno());
                merNo = merchantInfoMapper.getMerNo();
                //设置商户编号
                merchantInfoVo.setMerno(merNo);
                //设置终端绑定商户编号
                formalPosVo.setMerno(merNo);
                BeanUtils.copyBeanProp(newMerchant,merchantInfoVo);
                row = merchantInfoMapper.insertMerchantInfoVo(newMerchant);
                //商户附加表
                MerchantTotal mt = new MerchantTotal();
                mt.setMerno(merNo);
                mt.setAgentNum(merchantInfoVo.getAgentNo());
                merchantTotalMapper.insertMerchantTotal(mt);
            } else {
                formalPosVo.setMerno(merList.get(0).getMerno());
                LogUtils.logInfo("更新同步:" + merchantInfoVo.getLdMerno());
                BeanUtils.copyBeanProp(newMerchant,merchantInfoVo);
                row = merchantInfoMapper.updateMerchantInfoVo(newMerchant);
            }

            if (row < 1) {
                LogUtils.logInfo("商户同步失败:" + merchantInfoVo.getLdMerno());
                return AjaxResult.success("商户同步失败");
            }


            formalPosVo.setPosType(Integer.parseInt(posType));

            FormalPosVo newPos = new FormalPosVo();
            BeanUtils.copyBeanProp(newPos,formalPosVo);
            //绑定终端信息
            if (fpResult == null) {
                row = formalPosMapper.insertFormalPosVo(newPos);
            } else {
                row = formalPosMapper.updateFormalPosVo(newPos);
            }
            if (row < 1) {
                LogUtils.logInfo("商户同步失败:" + merchantInfoVo.getLdMerno());
                return AjaxResult.success("商户终端同步失败");
            }

            //更新终端状态
            BranchPos bp = new BranchPos();
            bp.setMachineNum(newPos.getMachineNum());
            bp.setIsbound(Long.parseLong("1"));
            branchPosMapper.updatePos(bp);


            LogUtils.logInfo("钱创付同步成功:" + merchantInfoVo.getLdMerno());
            return AjaxResult.success("同步成功");
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("同步失败,请重试-" + merchantInfoVo.getLdMerno());
        }
    }

    public static void main(String[] args) throws Exception {

        System.out.println(EncryptUtils.getDecrypt(String.valueOf("8214313D195A96D0A27CE53A8E24E38CE1DBCEEE45F5F682D12595F7EF312078D48D74E8ADFC4755EED1B39CD093A97A976ADB29BD7A6BBA8DF2E252D0DC2790BF92AD023F250E23ACF5147284F11F12C60D11C8DFE192CFBB788A3E28AAA9B3FBF46EAE6D86ECD57F5F1EAFAC63FA7655EB65B33E79EABDB9A6CA8837E3F4BCF59E9271D9F1B5057E8A4F9941D7975CEADD5522FBCF973B005B8C6AB06D04AA")));

    }

}
